Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Foreign key queries

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.

like image 620
Hulk Avatar asked Mar 27 '10 17:03

Hulk


2 Answers

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.

like image 191
Daniel Roseman Avatar answered Sep 28 '22 09:09

Daniel Roseman


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.
value_mart.criteria_set.all()

# ... or with a filter().
Criteria.objects.filter(header=value_mart)
Criteria.objects.filter(header_id=1)

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

like image 41
istruble Avatar answered Sep 28 '22 11:09

istruble