与Django一起,在Admin中代表foreignkeys

2024-06-28 20:53:43 发布

您现在位置:Python中文网/ 问答频道 /正文

构建一个通用应用程序来练习Django的学习。你知道吗

模型中有两个类:

class HouseInformation(models.Model):
        house_name = models.CharField(max_length=200)
        house_type = models.CharField(max_length=40)
        address = models.CharField(max_length=200)
        latitude = models.CharField(max_length=200)
        longitude = models.CharField(max_length=200)

        def __str__(self):
                return self.house_name

class HouseReport(models.Model):
        the_house = models.ForeignKey(HouseInformation)
        visit_date = models.DateField()

在Admin视图中,我想查看带有访问日期的房屋列表。这个管理员.py到目前为止是这样的,但它不起作用:

from django.contrib import admin
from housing.models import HouseInformation
from housing.models import HouseReport

class HouseReport(admin.ModelAdmin)
        list_display = ('the_house')

admin.site.register(HouseInformation, HouseReport)

我希望一对多是正确的代表(一个房子可以有很多访问)。你知道吗


Tags: thenamefromimportselfmodeladminmodels
2条回答

问题是缺少:

class HouseReport(admin.ModelAdmin):
                                   ^

谈到您最初想要解决的任务,请检查^{}类:

The admin interface has the ability to edit models on the same page as a parent model. These are called inlines.

将此添加到admin.py

from django.contrib import admin
from housing.models import HouseInformation, HouseReport


class HouseReportInline(admin.TabularInline):
    model = HouseReport

class HouseAdmin(admin.ModelAdmin):
    inlines = [
        HouseReportInline,
    ]

admin.site.register(HouseInformation, HouseAdmin)

您将在House管理页上看到House信息和与House相关的所有HouseReport。你知道吗

您忘记了:在第5行的类定义之后

class HouseReport(admin.ModelAdmin):

你必须写作

...
list_display = ('the_house',)
...

注意后面的逗号吗?它告诉python,它应该创建一个元组

相关问题 更多 >