如何拥有“城市”?根据“国家”的字段字段,而无需创建它们的表



我知道有几个这样的问题(比如这个),但没有一个能帮助我解决我的问题。

我想在我的模型中有一个城市和一个国家字段,其中城市的选择取决于国家;但是我不想把城市和国家定义为模型类。下面是我的代码:

from django.contrib.auth.models import User
from django.db import models
from django.forms import ChoiceField
from django_countries.fields import CountryField

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name="UserProfile")
    name = models.CharField(max_length=30, null=False, blank=False)
    picture = models.ImageField(upload_to='userProfiles/', null=False, blank=False)
    date_of_birth = models.DateTimeField(null=False, blank=False)
    country = CountryField()
    # city = ??
    national_code = models.IntegerField(max_length=10, null=False, blank=False)
    email = models.EmailField()
    def __str__(self):
        return '{}'.format(self.user.username)
    def __unicode__(self):
        return self.user.username

就像字段"country"是country = CountryField()一样,我想知道是否有一种方法可以在不定义class Country(models.Model)class City(models.Model)的情况下执行任务

你可以使用django-cities。

然而,这并不能解决输入逻辑的问题——如果您需要在表单中选择国家后过滤城市的话。你可以使用django-smart-selects,但是我不确定实现django-cities的复杂模型结构有多容易。

我有同样的问题,我使用django-cities-light填充城市和地区/国家,django-smart-selects用于过滤结果代码,如下所示,在管理和表单中运行良好:

from django.db import models
from cities_light.models import City
from cities_light.models import Region
from smart_selects.db_fields import ChainedForeignKey
class Address(models.Model):
    ....
    state = models.ForeignKey(Region, on_delete=models.CASCADE)
    city = ChainedForeignKey(City, chained_field="state", chained_model_field="region")

记得在INSTALLED_APPS中添加'cities_light'和'smart_selects'。还可以在url中添加'smart_selects'。

path('chaining/', include('smart_selects.urls')),

唯一的方法就是在你的模型中定义选择:

class UserProfile(models.Model):
    CITIES = (
        ('ny', 'New York'),
        ('sm', 'Santa Monica')
        # .. etc
    )
    city = models.CharField(max_length=5, choices=CITIES, blank=True)

更多文档

最新更新