如何在 Django 模型中根据“国家/地区”字段设置“城市”字段,而不创建其表

Far*_*Far 6 python django django-countries

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

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

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
Run Code Online (Sandbox Code Playgroud)

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

ger*_*ett 4

为此,您可以使用django-cities

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