【问题标题】:How to get related model data in Django Admin panel?如何在 Django 管理面板中获取相关模型数据?
【发布时间】:2020-11-27 18:33:57
【问题描述】:

我正在开发一个产品基表,我的product 表与Informtion 表相关,这意味着一个产品可以有信息,但是当我从管理面板添加产品时,我没有在那里获取信息数据提交产品,请告诉我如何在 django 管理面板中获取 product 中的 information 表字段。

这是我的 `models.py 文件...

class Product(models.Model):
    name=models.CharField(max_length=50, blank=True, null=True)
    type=models.CharField(max_length=50, blank=True, null=True)
    def __str__(self):
        return self.name

class Information(models.Model):
    product=models.ForeignKey(Product, default=None, related_name='product_info', on_delete=models.CASCADE)
    title=models.CharField(max_length=50, null=True, blank=True)
    number=models.IntegerField(default=None)

    def __str__(self):
        return self.title

我的 `admin.py' 文件是这个

from django.contrib import admin
from customer.models import *
# Register your models here.
admin.site.register(Product)
admin.site.register(Information)

当我点击add product 时,它只显示nametype,我还想显示information 表中的数据,当我点击add product 时,我想要所有字段

【问题讨论】:

    标签: django django-models django-views django-templates django-admin


    【解决方案1】:

    将此行添加到您的管理员:

    from django.contrib import admin
    
    class InformationInline(admin.TabularInline):
        model = Information
    
    class productAdmin(admin.ModelAdmin):
    
        inlines = [InformationInline]
    
    admin.site.register(Product,productAdmin)
    

    并删除以下行:

    admin.site.register(Product)
    

    现在重新启动服务器并进入您的管理员,现在您可以看到所有信息表数据并对其进行编辑。

    【讨论】:

    • 当我点击add product 时,仍然只获得Product 表数据,但我还想从information 表中添加数据......它只显示nametype 时我点击“添加产品”。
    • 这是唯一的方法..你一定犯了一些愚蠢的错误..请检查您的型号名称是否以大写字母开头。尝试使用 ProductAdmin 而不是 productAdmin 编辑代码
    • 它运行完美,但它给了我add another customer profile,我不想添加更多,请查看此屏幕截图https://prnt.sc/tvtsmm
    • 让它保持黑色..不要添加它..它很简单
    • 但我想从那里删除此字段
    【解决方案2】:

    你想要的叫做Inline。在此处阅读更多信息:Django Admin Inline

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 2012-05-21
      • 2012-06-22
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多