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 に答える