在Django管理中显示来自不同模型的相关字段,可以通过以下几种方法实现:
list_display
设置需要显示的字段。例如,有两个模型A和B,其中B模型包含一个指向A模型的外键字段,可以在B模型的管理页面中显示A模型的相关字段。from django.db import models
class A(models.Model):
field1 = models.CharField(max_length=100)
field2 = models.IntegerField()
class B(models.Model):
a = models.ForeignKey(A, on_delete=models.CASCADE)
field3 = models.CharField(max_length=100)
# admin.py
from django.contrib import admin
class BAdmin(admin.ModelAdmin):
list_display = ('field3', 'a_field1', 'a_field2')
def a_field1(self, obj):
return obj.a.field1
a_field1.short_description = 'Field 1 from A'
def a_field2(self, obj):
return obj.a.field2
a_field2.short_description = 'Field 2 from A'
admin.site.register(B, BAdmin)
list_display
中添加相关字段的方法名来显示。from django.db import models
class A(models.Model):
field1 = models.CharField(max_length=100)
field2 = models.IntegerField()
class B(models.Model):
field3 = models.CharField(max_length=100)
a = models.ManyToManyField(A, through='AB')
class AB(models.Model):
a = models.ForeignKey(A, on_delete=models.CASCADE)
b = models.ForeignKey(B, on_delete=models.CASCADE)
# admin.py
from django.contrib import admin
class ABInline(admin.TabularInline):
model = AB
class BAdmin(admin.ModelAdmin):
list_display = ('field3', 'a_field1', 'a_field2')
inlines = [ABInline]
def a_field1(self, obj):
return obj.a.field1
a_field1.short_description = 'Field 1 from A'
def a_field2(self, obj):
return obj.a.field2
a_field2.short_description = 'Field 2 from A'
admin.site.register(B, BAdmin)
list_display
显示该属性方法的返回值。同样,通过在list_display
中添加属性方法的方法名来显示。from django.db import models
class A(models.Model):
field1 = models.CharField(max_length=100)
field2 = models.IntegerField()
class B(models.Model):
field3 = models.CharField(max_length=100)
def a_field1(self):
return A.objects.get(b=self).field1
a_field1.short_description = 'Field 1 from A'
def a_field2(self):
return A.objects.get(b=self).field2
a_field2.short_description = 'Field 2 from A'
# admin.py
from django.contrib import admin
class BAdmin(admin.ModelAdmin):
list_display = ('field3', 'a_field1', 'a_field2')
admin.site.register(B, BAdmin)
无论采用哪种方法,都可以在Django管理中显示来自不同模型的相关字段。这样可以方便地查看和管理模型之间的关联数据。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云