如何在另一个类中表示类实例

时间:2018-02-01 05:35:46

标签: django

我是django的新手,我想在类别类别中表示类Item的实例(所以当我去披萨类别时,我想看到玛格丽塔披萨和任何其他创建的项目)

所以这是我的管理界面

admin interface

这是披萨类别

created category pizza

项目表中的项目玛格丽塔披萨

enter image description here

这是我的models.py代码

from django.contrib import admin 
from django.db import models


class Customer (models.Model):
    name = models.CharField(max_length=500)
    email = models.CharField(max_length=1000 , unique=True)
    phone = models.IntegerField()
    address = models.CharField(max_length=3000)


class Category(models.Model):
    name = models.CharField(max_length=100 , unique=True)

    def __str__(self):
        return self.name


class Order (models.Model):
    time = models.DateTimeField(auto_now_add=True)
    total = models.IntegerField()
    created_by = models.ForeignKey(Customer, related_name='orders')


class Item (models.Model):
    name = models.CharField(max_length=100 ,unique=True)
    details = models.CharField(max_length=1000)
    price = models.IntegerField()
    item_logo = models.ImageField(upload_to='res/images')
    category = models.ForeignKey(Category , related_name='items' , on_delete=    models.CASCADE)

    def __str__(self):
        return self.name

class ItemInline(admin.TabularInline):
    model = Item.name

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

admin.py

from django.contrib import admin
from .models import Category, Item , Order , Customer

admin.site.register(Category)
admin.site.register(Order)
admin.site.register(Item)

1 个答案:

答案 0 :(得分:0)

您应首先为项目创建内联管理类:

class ItemInline(admin.TabularInline):
    model = Item

然后,您可以将其添加到CategoryAdmin课程中:

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

并注册您的管理员类:

admin.site.register(Category, CategoryAdmin)

而不只是:

admin.site.register(Category)

希望它有所帮助。