在Django模型中订购多对多关系 [英] Ordering many-to-many relations in Django models

查看:138
本文介绍了在Django模型中订购多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您在Django模型中有多对多的关系,例如:

  class GroceryList(models。模型):
items = models.ManyToManyField(GroceryItem,related_name ='in_lists')

class GroceryItem(models.Model):
name = models.CharField(unique = True )

您和我都可以在两个不同的列表中拥有相同的项目,例如 Avocado ,他们将指向相同的鳄梨对象。



什么是为每个列表中的项目实施任意的订单的最佳方法,可以分别为每个列表编辑? (即我的列表中有 Avocado ,而您在索引 4



django-ordered-model 似乎是一个有趣的解决方案,但它假定所有对象的全局顺序。

解决方案

可以使用 through a>并在该表中添加有序字段。

  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( G roceryItem)

所以,而不是做 grocerylist.items.add(groceryitem)你可以做

  #for groceryitem1作为grocerylist1中的第一项
Order.objects.create (gl = grocerylist1,gi = groceryitem1,number = 1)

#for groceryitem1作为杂货店2中的第10个项目
Order.objects.create(gl = grocerylist2,gi = groceryitem1,number = 10 )


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

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

class GroceryItem(models.Model):
    name = models.CharField(unique=True)

You and me can both have the same items in two different lists, such as Avocado, and they will point to the same Avocado object.

What is the best way to implement an arbitrary order for items in each list, that can be edited separately for each list? (i.e. I have Avocado first in my list, while you have it at index 4)

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

解决方案

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)

这篇关于在Django模型中订购多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆