4

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

我想在我的模型中有一个 City 和 Country 字段,City 的选择取决于 Country;但我不想将 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

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

4

3 回答 3

2

为此,您可以使用django-cities

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

于 2016-10-01T14:08:45.083 回答
0

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

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

更多在文档中

于 2016-10-01T13:37:10.853 回答
0

我遇到了同样的问题,我使用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")

请记住将“cities_light”和“smart_selects”添加到 INSTALLED_APPS。还将“smart_selects”添加到 url。

path('chaining/', include('smart_selects.urls')),
于 2021-04-27T19:07:35.507 回答