0

How do i get the models / objects that relate to a model / object?

I know that a ForeignKey adds accessors. It would be enough to list them.

I have the usual ForeignKey Field szenario:

class Tag(models.Model):
   ...
   person = ForeignKey(Person)

class Person(models.Model):
   ...

I know i could write person_object.tag_set - the accessor added by the ForeignKey. But that's no option in a generic szenario.

It seems that the class ForeignObject offers a solution, but how do i use it?

dev langer
  • 202
  • 1
  • 11

1 Answers1

0

You have to use related_name to get the reverse relation.

class Tag(models.Model):
   ...
   person = ForeignKey(Person, related_name="tags")

class Person(models.Model):
   ...

Person.objects.all()[0].tags.all()

Sławek Kabik
  • 669
  • 8
  • 13