Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

python - Django - Access fields on a model's "through" table from an instance

I have a many-to-many relationship with a through table like so:

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

I am able to get the slides for a chapter in order like so:

chapter = Chapter.objects.get(pk=1)
chapter_slides = chapter.slides.order_by('slideorder')

However, when working on an individual slide instance I am unable to access the slide order:

slide = Slide.objects.get(pk=1)

If I do the following on my slide instance I can see all possible fields:

print slide._meta.get_all_field_names()
['title', u'chapters', 'slideorder', u'id']

However trying to access the slideorder field gives me the following:

slide.slideorder
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Slide' object has no attribute 'slideorder'

I am able to access all attributes listed except slideorder. How can I access a slide's order?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can either filter on the SlideOrder model directly

slide = Slide.objects.get(pk=1)
slide_orders = SlideOrder.objects.filter(slide=slide)
for slide_order in slide_orders:
    print slide_order.number

or follow the foreign key backwards:

slide = Slide.objects.get(pk=1)
slide_orders = slide.slideorder_set.all()
for slide_order in slide_orders:
    print slide_order.number

See the docs on extra fields on many-to-many relationships for more info.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...