Order many-to-many relationships in Django models

Suppose you have a many-to-many relationship in a Django model, for example:

class GroceryList(models.Model): items = models.ManyToManyField(GroceryItem, related_name='in_lists') class GroceryItem(models.Model): name = models.CharField(unique=True) 

You and I can have the same elements in two different lists, for example Avocado , and they will point to the same Avocado object.

What is the best way to implement a random order for items in each list that can be edited separately for each list? (i.e. I have Avocado first on my list, and you have index 4 )

The django-ordered-model seems like an interesting solution, but it assumes a global order across all objects.

+6
source share
1 answer

You can use the staging table with through and add an ordered field to this 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 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) 
+13
source

Source: https://habr.com/ru/post/957815/


All Articles