How to make Django ManyToMany relationships explicit on the receiving model's end

前端 未结 2 754
攒了一身酷
攒了一身酷 2021-01-20 18:26

Relationships, particularly ManyToMany, in Django have always bothered me somewhat. In particular, since the relationship is only defined in one of the models,

相关标签:
2条回答
  • 2021-01-20 19:07

    Found a way on Django's forum (lost link, sorry)

    class Topping(models.Model):
        explicit_pizza_set = models.ManyToManyField(Pizza, through=Pizza.toppings.through, blank=True)
    
    class Pizza(models.Model):
        toppings = models.ManyToManyField(Topping)
    
    0 讨论(0)
  • 2021-01-20 19:15

    This seems to be an unavoidable side effect of the DRY principle. I don't know of any way to declaratively show the symmetry in these relations (other than by commenting and such). If you really want to make things explicit you could put the relationship in its own table (which Django is doing behind the scenes anyway), like:

    class Topping(models.Model):
        # ...
    
    class Pizza(models.Model):
        # ...
    
    class PizzaToppings(models.Model):
        # '+' disables the reverse relationship
        pizza = models.ForeignKey(Pizza, related_name='+') 
        topping = models.ForeignKey(Topping, related_name='+')
    

    ... but of course then you'd lose some of the convenience of the ORM.

    0 讨论(0)
提交回复
热议问题