获取Django Admin中的状态下拉列表

时间:2011-02-06 02:22:10

标签: django django-admin

我为企业列表制作了一些基本模型,如下:

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)  
    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)  

在我编辑每个商家的管理员中,它显示了state_id字段。但是,如何将其与状态模型连接以显示状态的选择下拉列表?

另外,如何在业务视图中显示州缩写?

3 个答案:

答案 0 :(得分:8)

不需要单独的状态表的替代方案:

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)  
    ...

答案 1 :(得分:4)

2015年编辑(django 1.8)

你应该查看django官方localflavor repo:https://github.com/django/django-localflavor

from localflavor.us.models import USStateField

class Business(models.Models):
    …
    state = USStateField(null=True, blank=true)
    …

某些tests are available on the repo用于此特定用途。

答案 2 :(得分:2)

您需要使用ForeignKey字段。 进行以下更改。

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

默认情况下,在数据库中创建列名时,ForeignKey字段会在字段名称后附加“_id”。因此,Business类中的新“state”字段将自动使用您之前定义的“state_id”列,除非您更改了Django的某些默认行为。

有关此内容的更多信息:

  1. 查看Django's documentation of the ForeignKey field
  2. stackoverflow.com上的
  3. Search "ForeignKey"