如何在Django / Admin中显示相关对象? [英] How to show related objects in Django/Admin?

查看:95
本文介绍了如何在Django / Admin中显示相关对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个模型:

from django.db import models

class Category(models.Model):
    icon = models.ImageField(upload_to = 'thing/icon/')
    image = models.ImageField(upload_to = 'thing/image/')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=200)
    slug = models.SlugField()
    desc = models.TextField(max_length=1000)

    def __str__(self):
        return self.title

    def __unicode__(self):
        return self.title

class Thing(models.Model):
    icon = models.ImageField(upload_to = 'thing/icon/')
    image = models.ImageField(upload_to = 'thing/image/')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=200)
    slug = models.SlugField()
    desc = models.TextField(max_length=1000)
    content = models.TextField()
    category = models.ForeignKey('Category')

    def __str__(self):
        return self.title

    def __unicode__(self):
        return self.title

我正在使用Django的管理站点进行基本的CRUD操作。如果要在管理员中选择类别,则需要显示类别中的所有内容。

I am using Django's admin site for basic CRUD operations. I need to show all Things in Category if I am selecting an Category in admin.

推荐答案

您可以使用内联来可视化并在该类别的管理员详细信息中编辑某个类别的事物:

You can use "Inlines" to visualize and edit Things of a certain Category in the admin detail for that category:

在admin.py文件中,为Thing创建一个内联对象(ThingInline)并修改CategoryAdmin类具有ThingInline类型的内联,例如:

In the admin.py file, create an Inline object for Thing (ThingInline) and modify your CategoryAdmin class to have an inline of type ThingInline like this:

...
class ThingInline(admin.TabularInline):
    model = Thing

class CategoryAdmin(admin.ModelAdmin):
    inlines = [
        ThingInline,
    ]
...

有关更多详细信息,这是管理员内联的文档: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects

For further details, this is the docs for admin inlines: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects

这篇关于如何在Django / Admin中显示相关对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆