我和通过这样的表有很多对多的关系:
class Chapter(models.Model):
name = models.CharField(max_length=255,)
slides = models.ManyToManyField('Slide', blank=True, related_name='chapters', through='SlideOrder')
# ...
class Slide(models.Model):
title = models.CharField(max_length=255,)
# ...
class SlideOrder(models.Model):
chapter = models.ForeignKey(Chapter)
slide = models.ForeignKey(Slide)
number = models.PositiveIntegerField()
我可以按顺序获取章节的幻灯片:
chapter = Chapter.objects.get(pk=1)
chapter_slides = chapter.slides.order_by('slideorder')
但是,在处理单个幻灯片实例时,我无法访问幻灯片订单:
slide = Slide.objects.get(pk=1)
如果我在幻灯片实例上执行以下操作,我可以看到所有可能的字段:
print slide._meta.get_all_field_names()
['title', u'chapters', 'slideorder', u'id']
但是,尝试访问slideorder
字段会给我以下内容:
slide.slideorder
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Slide' object has no attribute 'slideorder'
我可以访问除slideorder
以外的所有列出的属性。如何访问幻灯片的订单?
答案 0 :(得分:2)
您可以直接过滤SlideOrder
模型
slide = Slide.objects.get(pk=1)
slide_orders = SlideOrder.objects.filter(slide=slide)
for slide_order in slide_orders:
print slide_order.number
或向后关注外键:
slide = Slide.objects.get(pk=1)
slide_orders = slide.slideorder_set.all()
for slide_order in slide_orders:
print slide_order.number
有关详细信息,请参阅extra fields on many-to-many relationships上的文档。
答案 1 :(得分:1)
您可以使用django docs
中记录的slide.slideorder_set