Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python “如何拥有”;“城市”;字段取决于;国家“;Django模型中的字段,而不创建它们的表_Python_Django_Django Countries - Fatal编程技术网

Python “如何拥有”;“城市”;字段取决于;国家“;Django模型中的字段,而不创建它们的表

Python “如何拥有”;“城市”;字段取决于;国家“;Django模型中的字段,而不创建它们的表,python,django,django-countries,Python,Django,Django Countries,我知道有几个问题是这样问的(比如),但没有一个能帮我解决问题 我想在我的模型中有一个城市和一个乡村,城市的选择取决于乡村;但我不想将城市和国家定义为模型类。这是我的密码: from django.contrib.auth.models import User from django.db import models from django.forms import ChoiceField from django_countries.fields import CountryField cla

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

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

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()
)一样,我想知道是否有一种方法可以在不定义
类国家(models.Model)
类城市(models.Model)

的情况下完成任务,唯一的方法是在您的模型中定义选项:

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

要做到这一点,您可以使用


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

我也遇到了同样的问题,我曾经填充城市和地区/国家,用于过滤生成的代码是这样的,并且在管理和表单中运行良好:

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")
请记住在已安装的应用程序中添加“城市照明”和“智能选择”。 还将“智能选择”添加到URL

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

您想在模型中包含城市和国家字段,但不想定义它们?:)即使是来自django_countries的
。字段导入CountryField
也会创建字段,那么您希望如何保存数据库中没有字段的数据?@doniyor-不,我的意思是我希望在模型中包含城市和国家字段,但不希望为城市或/和国家定义整个表;因为我不需要它们,我只想把它们作为我的“UserProfile”模型的一个字段