class Data(models.Model):
user = models.ForeignKey(User, unique=True)
name = models.CharField(null=False, max_length=250)
class OtherData(models.Model):
user = models.ForeignKey(User, unique=True)
something = models.CharField(max_length=250)
如何在Django Admin中创建类似堆栈内联但没有外键的东西?
如果我在管理页面中查看Data
对象,我还要查看OtherData
对象(属于同一用户)
答案 0 :(得分:0)
如果您想在同一表单上管理Data和OtherData,那么:
以下是示例代码
from django.contrib.admin import StackedInline
from django.contrib.auth.models import User
from models import Data, OtherData
class DataInline(StackedInline):
model = Data
#form = you can customize your form
#max_number = define the number of inlines
class OtherDataInline(StackedInline):
model = OtherData
class UserAdmin(admin.ModelAdmin):
inlines = (DataInline, OtherDataInline,)
fields = ('username',)
readonly_fields = ('username',)
#the user can be regitered just once in the admin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
如果用户有多个Data或OtherData,您可能想尝试使用TabularInline。换句话说,如果模型中有一对多关系。 Inlines的灵活性令人难以置信。