Skip to content

Instantly share code, notes, and snippets.

@raiderrobert
Last active June 10, 2016 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raiderrobert/881636c6a90361f6e1b04dda5810f166 to your computer and use it in GitHub Desktop.
Save raiderrobert/881636c6a90361f6e1b04dda5810f166 to your computer and use it in GitHub Desktop.
Selected Related Example with Querysets
from django.db import models
from localflavor.us.models import USStateField
class State(models.Model):
name = USStateField(unique=True)
incits_code = models.CharField(max_length=250)
class Meta:
ordering = ['name', ]
class County(models.Model):
name = models.CharField(max_length=250)
state = models.ForeignKey(State)
objects = CountyManager()
class Meta:
verbose_name_plural = 'Counties'
unique_together = ('name', 'state')
ordering = ['name', ]
def __unicode__(self):
return self.county_and_state_display
@property
def county_and_state_display(self):
"""
Returns a human-readable display of counties and states
"""
return u'{0}, {1}'.format(self.name, self.state)
class CountyManager(models.Manager):
def get_queryset(self):
return super(CountyManager, self).get_queryset().select_related('state')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment