2 回答
TA贡献1936条经验 获得超6个赞
您可以为此目的使用外键。
然后您的代码将与此类似:
class Car(models.Model):
# some code here
class DetailInfo(models.Model):
car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='details')
detail_name = models.CharField(max_length=200)
detail_desc= models.CharField(max_length=200)
然后您可以通过以下方式查看所有详细信息:
car = Car.objects.first() # just example, load first instance of Car
detail_infos = car.details.all() # now detail_infos include queryset of all DetailInfo instances, that connected to Car
在django admin中,您可以添加details为内联(例如,请参见此链接)。
例子
# admin.py
from django.contrib import admin
from .models import Car, DetailInfo
class DetailInfoInline(admin.TabularInline): # you can use admin.TabularInline or admin.StackedInline here
model = DetailInfo
@admin.register(Car) # shortcut for admin.site.register()
class CarAdmin(admin.ModelAdmin):
inlines = [DetailInfoInline]
TA贡献1829条经验 获得超13个赞
按照我更新的 TabularInline 的代码
admin.py
class DetailInfoInline(admin.TabularInline):
model = DetailInfo
class ShowCaseAdmin(admin.ModelAdmin):
inlines = [
DetailInfoInline,
]
models.py
class DetailInfo(models.Model):
link = models.CharField(max_length=200)
showcase = models.ForeignKey(ShowCase, on_delete=models.CASCADE, related_name='details')
添加回答
举报