2👍
✅
You need to use a ForeignKey field.
Make the following changes.
class Business(models.Models):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=225, blank=True)
address = models.CharField(max_length=150, blank=True)
city = models.CharField(max_length=150, blank=True)
#state_id = models.IntegerField(null=True, blank=True)
# Define a new state field that creates a ForeignKey relationship with States
state = models.ForeignKey('States', null=True, blank=True)
zip = models.CharField(max_length=33, blank=True)
country = models.CharField(max_length=150, blank=True)
url = models.CharField(max_length=765, blank=True)
class States(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=96)
state_abbr = models.CharField(max_length=24, blank=True)
#Define the __unicode__ method, which is used by related models by default.
def __unicode__(self):
return self.state_abbr
By default ForeignKey fields append ‘_id’ to the field name when creating the column name in the database. So, the new “state” field in the Business class will automatically use the column “state_id” that you’ve previously defined, unless you’ve changed some of the default behavior of Django.
For more on this:
- Check out Django’s documentation of
the ForeignKey field - Search “ForeignKey” on stackoverflow.com
11👍
An alternative that doesn’t require a separate state table:
from django.contrib.localflavor.us.us_states import STATE_CHOICES
class Business(models.Models):
...
state = models.CharField(max_length=2, choices=STATE_CHOICES, null=True, blank=True)
...
👤Dave
- [Django]-Refactor this Python code to iterate over a container
- [Django]-Why I am Getting '_SIGCHLDWaker' object has no attribute 'doWrite' in Scrapy?
- [Django]-Remove the decimal part of a floating-point number in django?
7👍
Edit in 2015 (django 1.8)
you should check the django official localflavor repo: https://github.com/django/django-localflavor.
from localflavor.us.models import USStateField
class Business(models.Models):
…
state = USStateField(null=True, blank=True)
…
Some tests are available on the repo for this specific usage.
Docs available here.
- [Django]-Multiple User Profiles in django-userena
- [Django]-What is the best way to consume a django-piston REST API from a Django view?
- [Django]-What would be the best way to track Github account activity via their API?
- [Django]-Django: how to map the results of a raw sql query to model instances in admin list view?
- [Django]-Django admin to edit foreign keys inline
Source:stackexchange.com