Ordering many-to-many relations in Django models

后端 未结 1 1526
长发绾君心
长发绾君心 2021-01-05 09:15

Suppose you have a many-to-many relation in a Django model, such as:

class GroceryList(models.Model):
    items = models.ManyToManyField(GroceryItem, related         


        
1条回答
  •  囚心锁ツ
    2021-01-05 09:44

    You can use the intermediate table using through and add the ordered field in that table.

    class GroceryList(models.Model):
        items = models.ManyToManyField(GroceryItem, related_name='in_lists', 
                through='Order')
    
    class GroceryItem(models.Model):
        name = models.CharField(unique=True)
    
    class Order(models.Model):
        number = models.PositiveIntegerField()
        gl = models.ForeignKey(GroceryList)
        gi = models.ForeignKey(GroceryItem)
    

    So instead of doing grocerylist.items.add(groceryitem) you can do

    #for groceryitem1 as 1st item in grocerylist1
    Order.objects.create(gl=grocerylist1, gi=groceryitem1, number=1)
    
    #for groceryitem1 as 10th item in grocerylist2
    Order.objects.create(gl=grocerylist2, gi=groceryitem1, number=10)
    

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