gpt4 book ai didi

Django:如何通过自定义 Django_Admin 动态过滤外键选择

转载 作者:行者123 更新时间:2023-12-04 19:52:23 25 4
gpt4 key购买 nike

我有三个模型:LineType、Service、DomainName、Record,它们之间有 m2m 或外键关系。这是代码:

class LineType(models.Model):
linename = models.CharField(max_length=30,primary_key=True)

def __unicode__(self):
return self.linename

class Service(models.Model):
servicename = models.CharField(max_length=30,primary_key=True)
price = models.DecimalField(max_digits=8, decimal_places=2)
line = models.ManyToManyField(LineType)

def __unicode__(self):
return self.servicename

class DomainName(models.Model):
domainname = models.CharField(max_length=30,primary_key=True)
user = models.ForeignKey(SiteProfile)
service = models.ForeignKey(Service)

def __str__(self):
return self.domainname

class Record(models.Model):
TYPE_CHOICES = (
('A','A'),
('CNAME','CNAME'),
('MX','MX'),
)
domainname = models.ForeignKey(DomainName)

def get_line(self):
domain = DomainName.objects.get(pk=self.domainname_id)
service = Service.objects.get(pk=domain.service_id)
lines = service.line.all()
choices = []
for x in lines:
choices.append((x.linename,x.linename))
return choices

host = models.CharField(max_length=30)
type = models.CharField(max_length=5,choices=TYPE_CHOICES,default='A')
line = models.ForeignKey(LineType)
destaddress = models.CharField(max_length=30)

让我介绍一下模型。每个域名只能有一个服务,其他域名可以有。每个域名有多个记录。服务定义可应用于记录的 LineType。

我使用django admin来管理这些模型,但是Record中的“line”选择的都是LineType对象。所以问题是如何根据它的parent(DomainName)的“service”来过滤Record的LineType。

最佳答案

取决于您的确切要求和您的 Django 版本,答案可能是设置 limit_choices_to attribute of the foreign key ,或自定义 ModelAdmin 表单:

使用 limit_choices_to
只需将线路选择限制为那些匹配的 linename == 'foo'

class Record(models.Model):
# ...
line = models.ForeignKey(LineType, limit_choices_to={'linename': 'foo'}))

使用自定义 form
如果实例化表单时存在实例,我们可以选择它的域服务行作为查询集选择
class RecordAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RecordAdminForm, self).__init__(*args, **kwargs)

# access object through self.instance...
if self.instance:
valid_lines = self.instance.domainname.service.line.objects.all()
self.fields['line'].queryset = valid_lines

class RecordAdmin(admin.ModelAdmin):
form = RecordAdminForm
# ...

引用SO问题:
  • how to limit the foreignkey dropdown with constraints?
  • How do I filter ForeignKey choices in a Django ModelForm?
  • 关于Django:如何通过自定义 Django_Admin 动态过滤外键选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089168/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com