disruptive
disruptive

Reputation: 5946

Getting django record by foreign key

I have the following relationships:

class AMe(models.Model):
    Field1                  = models.CharField(max_length=50, choices = Field1_CHOICES)
    Field2                  = models.CharField(max_length=50, choices = Field2_CHOICES)

class MP(models.Model):
    MyAMeID                 = models.ForeignKey(AMe)
    Field1                  = models.CharField(max_length=50, choices = Field1_CHOICES)

Now the issue is that I want to select the records in the MP by the foreign-key i.e. MyAme, but the FK is not the same as the primary key of AMe, so what is a foolproof way of selecting the record in MP? Should I use the queryset and filter option? Or is there a smarter way, more Django way of doing this that I have missed?

Upvotes: 0

Views: 165

Answers (1)

Maciej Gol
Maciej Gol

Reputation: 15854

You can either use my_AMe_object.mp_set.all() (Django automatically creates reverse relations for ForeignKey fields by concatenating the model's name - here mp - and _set, can be set directly by related_name field attribute), or MP.objects.filter(MyAMeID=my_AMe_object).

Example usage of the reverse relation:

>>> from test_app.models import AMe, MP
>>> ame = AMe.objects.create()
>>> for _ in xrange(6):
...     MP.objects.create(MyAMeID=ame)
>>> ame.mp_set.all()
[<MP: MP object>, <MP: MP object>, <MP: MP object>, <MP: MP object>, <MP: MP object>, <MP: MP object>]

Note that mp_set returns a QuerySet object despite the number of results (similar to regular Model.objects.all() method).

Upvotes: 3

Related Questions