Py学习  »  Django

Django管理员网站:无法在“父模型”或“父模型管理员”上查找“子模型”

Sirc.Sbat • 3 年前 • 1116 次点击  

这个问题真的很难作为一个问题来写,因为我不确定一开始该怎么问。但我会努力的。基本上,当我在django管理站点中访问父模型时,我遇到了AttributeError。我当前的django数据库有两个表(除了预构建的表):一个用于活动的父表/模型,一个用于指令的子表/模型。这是我的模型的结构:

class activity(models.Model):
    title = models.CharField(max_length=30,default=None)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User,on_delete=models.CASCADE,default=None)

    def __str__(self):
        return self.__class__.__name__

class instruction(models.Model):
    detail = models.CharField(max_length=50,default=None)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User,on_delete=models.CASCADE,default=None)
    activity = models.ForeignKey(activity,on_delete=models.CASCADE,default=None)

    def __str__(self):
        return self.__class__.__name__

因此,如果我在django管理站点中添加一个新的活动,比如:俯卧撑,那么,我应该能够在指令表单中选择这个新添加的父记录。但是,当我尝试添加新的指令记录并选择保存的活动记录时,“活动”下拉列表仅显示模型的名称(在本例中为“活动”)。它不显示俯卧撑。接下来我做的是为活动和说明添加一些modelAdmins。以下是代码:

class activityAdmin(admin.ModelAdmin):
    list_display = [field.name for field in activity._meta.get_fields()]

class instructionAdmin(admin.ModelAdmin):
    list_display = [field.name for field in instruction._meta.get_fields()]

admin.site.register(activity, activityAdmin)
admin.site.register(instruction, instructionAdmin)

但是,当我这次访问管理站点的活动页面时,该页面会抛出一个AttributeError异常,其值为 Unable to lookup 'instruction' on activity or activityAdmin .说明页上不会出现这种情况。我意识到,这可能不是在指令表中显示活动标题的方法。不过,我需要在admin中添加modelAdmin。以显示管理站点中每个模型的所有字段。总之:

1. I need to display the parent model's field value (activity title) as an option in the child model's dropdown and not only the name of the parent model
2. I need to display the fields of each models on their respective registries in the admin site
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130830
 
1116 次点击  
文章 [ 1 ]  |  最新文章 3 年前
jmcarson
Reply   •   1 楼
jmcarson    3 年前

尝试更新你的 str 释义这用作下拉显示值,您当前正在设置类名。如果要在下拉列表中显示标题:

class activity(models.Model):
    title = models.CharField(max_length=30,default=None)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User,on_delete=models.CASCADE,default=None)

    def __str__(self):
        return self.title