[Solved]-Django Foreign key queries


First of all, don’t use id in the names, because it is confusing. That field isn’t the ID, it is the object itself. (If you have a field ref it automatically creates a field ref_id)


You query it like any value, where some header instance is the value you are filtering on.


Ironfroggy is right, but there is another more obvious way to get the relevant options and criteria objects. Django automatically creates a ‘reverse relation’ for every foreign key pointing at a model, and that is usually the name of the related model plus _set. So:


will give you all the options and header objects related to a criteria object mycriteria.

Also, a note on style: as ironfroggy pointed out, you shouldn’t use id in the foreign key fields, but also you should use Capitalised style for your model classes, so you can see a difference between the class Criteria and a particular instance criteria.

In terms of links, the Django documentation is excellent and explains all of this.


I would suggest trying to us a coding style and naming convention that is more like you see in the Django documentation for Models. Something more like this:

class Header(models.Model):

class Criteria(models.Model):
    details = model.CharField(max_length=255)
    header = models.ForeignKey(Header)

And then query them as needed:

# find Criteria for a given header
value_mart = Header.objects.get(id=1)

# ... via an instance of Header.

# ... or with a filter().

The documentation for many-to-one relationships also references a usage example.


Sounds like you are looking for Following relationships “backward”.

You can get the header object you want to filter by, and use something like

obj = Header.objects.get(title="value-mart", "createdby=CEO")

Look at the documentation for more detailed info

Leave a comment