M2M relationships to self with attribute.

时间:2017-10-12 10:01:45

标签: python django orm m2m

I want to create cross selling product:

class Product(models.Model):
    name = models.CharField(max_length=150, blank=True, default='')
    ...

class CrossSellingProduct(models.Model)
    parent_product = models.ForeignKey(Product, related_name='cross_sellings')
    associate_product = models.ForeingKey(Product)
    double_sided = models.BooleanField(default=1)

I want to call function cross_selling_products on product instance and see all products which are associated. If double_sided is True I can see associated product in bouth way, if False only parent -> associated_products.

Is some smart way to implement this? Thank you.

1 个答案:

答案 0 :(得分:0)

So basically you want to implement a ManyToMany-relation from the model Product to itsself? You can do that by

class Product(models.Model):
    name = models.CharField(max_length=150, blank=True, default='')
    cross_selling_products = models.ManyToManyField("self")
    ...

Then you can access the cross_selling_products on a Product's instance.