我有两个型号。我希望第一个模型的字段是第二个模型的字段的选择列表。但是二级模型领域并不是唯一的。
想想,需要以管理员形式重新划分字段
请帮助我认识到这一点。我正在学习django。
country models.py
from django.db import models
from django.contrib.auth.models import User
class Country(models.Model):
class Meta():
db_table = 'country'
country_region = models.CharField(max_length=300)
country_city = models.CharField(max_length=300)
country_district = models.CharField(max_length=300, blank=True, null=True)
client models.py
from django.db import models
from django.contrib.auth.models import User
from client.models import Client
# Create your models here.
class Client(models.Model):
class Meta():
db_table = 'client'
client_name = models.CharField(max_length=300)
client_region = models.CharField(max_length=300) #maybe ForeignKey
我想在admin
中的client_region(来自国家/地区)中选择列表(选项)我正在尝试使用admin.py
from django.contrib import admin
from country.models import Country
from client.models import Client
class ClientAdmin(admin.ModelAdmin):
def __init__(self, *args, **kwargs):
new_choices = Country.objects.values('country_region').distinct()
super(ClientAdmin.form, self).__init__(*args, **kwargs)
self.field['client_region'].choices = new_choices
# Register your models here.
admin.site.register(Client, ClientAdmin)
我尝试使用此代码,但这不起作用
admin.py
from django.contrib import admin
from timetable.models import Client
from house.models import Country
from django.forms import ModelChoiceField, ModelForm, forms
class ClientForm(ModelForm):
class Meta:
model = Client
def __init__(self, *args, **kwargs):
super(ClientForm, self).__init__(*args, **kwargs)
self.field['client_region'] = forms.ModelChoiceField(queryset=Country.objects.values['county_region'])
class ClientAdmin(admin.ModelAdmin):
list_display = ['client_region']
form = ClientForm
# Register your models here.
admin.site.register(Client, ClientAdmin)
答案 0 :(得分:0)
对于你想要做的事情(如果我理解,按地区获取客户列表),我的方式是创建第三个模型“Region”,并将Client和Country链接到此模型ForeignKey的。
我不太清楚你的问题很清楚,你能尝试重新制定吗?