简体   繁体   English

Django python中的自定义管理员下拉菜单

[英]Customized admin drop down menu in Django python

I am just a beginner in python. 我只是python的初学者。 I have created two admin services called child and parent. 我创建了两个名为child和parent的管理服务。

Parent - Table 父级-表格

id ID

name 名称

type 类型

Child - Table 儿童-桌子

pid pid

type 类型

cname 名字

In both services column "type" will be displayed in the drop down list. 在这两个服务列中,“类型”将显示在下拉列表中。 When creating an entry for parent, if the "type" was not chosen in the parent service. 为父项创建条目时,如果未在父项服务中选择“类型”。 That unchosen Parent id's should shown the in the child service in dropdown Sorry for my bad english 那个未选择的父母身份证应该在下拉菜单的子服务中显示抱歉,我的英语不好

# models.py

class Parent(models.Model):

    id = models.IntegerField(blank=False)

    type = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        related_name='parent_set')
   name = models.CharField(max_length=20)


class Child(models.Model):

    pid = models.IntegerField(max_length=30, blank=False)
    Type = models.ForeignKey(
         Parent,
         null=True, 
         on_delete=models.CASCADE, 
         related_name='child_set' )
    pname = models.CharField(max_length=20)

Any help would be appreciated 任何帮助,将不胜感激

haven't tested this. 还没有测试 Please check if this works. 请检查是否可行。

class ChildAdmin(admin.ModelAdmin):
    def render_change_form(self, request, context, *args, **kwargs):
         chosen_types = Parent.objects.all().values_list('type', flat=True)
         context['adminform'].form.fields['Type'].queryset = Parent.objects.all().exclude(pk__in=chosen_types)
         return super(ChildAdmin, self).render_change_form(request, context, args, kwargs)         

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM