Django Foreign key queries


Question

In the following model:

class header(models.Model):
    title = models.CharField(max_length = 255)
    created_by = models.CharField(max_length = 255)

    def __unicode__(self):
        return self.id()

class criteria(models.Model):
    details =   models.CharField(max_length = 255)
    headerid = models.ForeignKey(header)

    def __unicode__(self):
        return self.id()

class options(models.Model):
    opt_details =   models.CharField(max_length = 255)
    headerid = models.ForeignKey(header)

    def __unicode__(self):
        return self.id()

If there is a row in the database for table header as Id=1, title=value-mart , createdby=CEO

How do I query criteria and options tables to get all the values related to header table id=1

Also can some one please suggest a good link for queries examples.

1
10
9/29/2016 3:19:02 PM

Accepted Answer

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)

options.objects.filter(header=a_header)

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

9
3/27/2010 5:34:36 PM

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:

mycriteria.options_set.all()
mycriteria.header_set.all()

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon