jeff
jeff

Reputation: 13653

How to get tags of object via relation model in Django?

I have 3 models like this :

Entry:
    text = TextField(..)
    ...

Tag:
    text = CharField(..)
    ...

EntryTag
    entry = ForeignKey(Entry)
    tag = ForeignKey(Tag)

based on EntryTag objects, I want to populate any Entry object with .tags field, i.e. :

for e in myEntries:
    e.tags = Tag.objects.filter(?) # how do I select which tags are related to e?

How can I do this?

Thanks,

Upvotes: 1

Views: 40

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52153

Assuming you haven't set custom related_name value for any of your FK fields:

Tag.objects.filter(entrytag_set__entry=e)

Upvotes: 1

Related Questions