【发布时间】:2012-06-12 20:18:06
【问题描述】:
我正在写一个画廊领域。该字段子类ManyToManyField 并添加了自己的ajax 小部件和东西。我想让这个解决方案尽可能紧凑(我的意思是——如果可能的话,我想编写尽可能少的代码来在另一个项目中重新实现它)。
我决定创建一个中间表(向ManyToManyField 提供一个“通过”参数),它将保存订购信息:
class IntermediateModel(models.Model):
from_content_type = models.ForeignKey(ContentType)
from_object_id = models.PositiveIntegerField()
from_content_object = generic.GenericForeignKey('from_content_type', 'from_object_id')
to_content_type = models.ForeignKey(ContentType)
to_object_id = models.PositiveIntegerField()
to_content_object = generic.GenericForeignKey('to_content_type', 'to_object_id')
order = models.PositiveIntegerField()
出现以下问题:
- 是否可以在 django 中为 m2m 提供一个“直通”模型,让两个外键都指向一个通用关系(如上面的那个)?如果是这样 - 如何实现?
- 如果可以做到这一点 - 这种模型能否在多个 m2m 字段之间保持通用关系?喜欢:班级 中级 学生、画廊 中级 照片 - 都使用中级作为“通过”模型??
- 编辑:刚刚测试过 - 我可以 ;) 我可以将抽象类与“通过”表一起使用吗?我想通了——如果上面提到的复杂场景不起作用,我可以创建两个提供排序和其他东西的抽象类,然后总是创建普通的子类来实际建立一些关系:)
【问题讨论】:
标签: django django-models many-to-many django-orm