django how to add to my model a field list of its own model?

458 Views Asked by At

I am making a model, where will represent a product but I want to add a field with complementary_products, that I want to make it a list of product.

for example,

id: 1 

product: dr pepper

complementary_products [chips, hotdogs]

id: 2

product: laptop

complementary_products" [mouse, usb_cable]

id: 3

product: chips

complementary_products [dr pepper, hotdogs]

I was trying many to many, but when I start adding prodcuts in the admin page, keeps appending, if I add 3 items, the last one will have all the first ones =(

class ProductModel(models.Model):
    product_name = models.CharField(max_length=200)
    complementary_products = models.ManyToManyField("self", blank=True)

if I use ForeingKey, I can only set to just one item =(

complementary_products = models.ForeignKey("self", on_delete=models.CASCADE, default=None, blank=True)

any recommendation on how can achieve this? thanks guys

enter image description here

when I try to add the third product, the field already have the 2 previews one I do get the + sign button to keep adding more products, but I dont have a button to delete, is because might be something wrong with admin form of Django?

2

There are 2 best solutions below

1
Taylor On

If I understand your question correctly it sounds like you need many to many with a though table. The docs does a good job at explaining it so I will not go into it here.

Example

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):
        return self.name

class CompProduct(models.Model):
    name = models.CharField(max_length=128)
    products = models.ManyToManyField(Product, through='ProductsBelong')

    def __str__(self):
        return self.name

class ProductsBelong(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    comp = models.ForeignKey(CompProduct, on_delete=models.CASCADE)
    date_added = models.DateField()
 
0
pelos On
class ProductModel(models.Model):
    product_name = models.CharField(max_length=200, null=True)
    complementary_products = models.ManyToManyField("self", blank=True)  # , related_name="products")

if set related_name= argument you can tell Django the name of the table to create behind doors. plus I wasn't Control+clicking on the complementary_products list