Django ManyToManyFiled how to add 2 objects of the same type to a model

0

I'm doing an inventory of tools, and I want to have a way to create a tool cart where I can add repeated tools. Example (Add to the cart two cutters of the same type).

I have a table called Item This table contains all the common fields of all the tools (description, quantity_existing, minimum quantity, unit price, etc.) and a table for each type of tool ( clamps, cutters, screwdrivers, screws, etc.) the tables for the tools inherit from the Item table.

I also have a table called Carts and Employees . In the table Carritos I seek to make the union of Items and Employees . I do not plan to generate a view since I want to control the creation of carts and the assignment of employees from the Admin page, for the moment I can select different tools in the cart, what I can not do is put more of the same type or manually put the amount of that type of tool that the cart has

models.py

# =========================================================================== #
#   MODELO PARA CREAR CARRITOS
# =========================================================================== #

class Carritos(models.Model):
    no_carrito = models.CharField(max_length=3, unique=True)
    empleado = models.ForeignKey(Empleados, on_delete=models.CASCADE)
    herramienta = models.ManyToManyField(Item)
    # cantidad = models.PositiveIntegerField()
    f_creacion = models.DateTimeField(auto_now_add=True)
    f_actualizacion = models.DateTimeField(auto_now=True)
    activo = models.BooleanField(default=True)


    class Meta:
        verbose_name_plural = "Carritos"

    def __str__(self):
        return self.no_carrito

I would really appreciate your help

    
asked by victorR 17.07.2018 в 23:26
source

1 answer

0

Interesting your question. Everything you need you can find here . It is very common to find this type of situation where you need to relate two or more times one table with another.

First I want to give you the situation of what happens. You have a record of the model or table Item , let's say it is a 'Hammer'. When your cart is going to make a purchase of that hammer, the customer probably only wants to take 1 hammer product of many that you must have. Right now, what happens is that the client is taking all the hammers, because you do not keep a record of it. Ideally, somewhere in your relationship you could set the amount, it probably will not be necessary to have two relationships with the same Item ('Hammer'), since in your database you will have in that record a repeated index.

To solve your problem there is something called Intermediate Tables (At least that's how I know it). It consists of making a relationship with another table (which actually already exists, only it is something I would imagine) and this table is responsible for creating the relationship of your models. How does this work? I'll give you a first practical example:

class Carrito(models.Model):
   # tus campos
   items = models.ManyToMany('Item', through='ItemCarrito', related_name='carritos')
   ...

class Item(models.Moldel):
   # tus campos
   ...

class ItemCarrito(models.Model):
   carrito = models.ForeignKey(Carrito, related_name='items_carrito')
   item = models.ForeignKey(Item, related_name='items_carrito')
   cantidad = models.PositiveSmallIntegerField()

I do not know if you know, but when you create a foreign key relationship or Foreign Key what you do is create a one-to-many relationship. That is, if ItemCarrito has a foreign key with Carrito and with Item it means that:

# * => * (Relación de muchos a muchos)

Carrito * => * ItemCarrito 
Item * => * ItemCarrito
(Entonces) Carrito * => * Item

This way you have solved what you need. To prove it, it would be enough to do this:

martillo = Item.objects.create(name='martillo')
regleta = Item.objects.create(name='regleta')

carrito = Carrito()
ItemCarrito.objects.create(carrito=carrito, item=martillo, cantidad=2)
ItemCarrito.objects.create(carrito=carrito, item=regleta, cantidad=1)

carrito.items_carrito.all()
    
answered by 18.07.2018 / 01:14
source