Django模型允许多个

所以我想创建一个模型,假设“汽车”我想实现字段 detail_name 和 detail_desc

detail_name  = models.CharField(max_length=200)
detail_desc= models.CharField(max_length=200)

但我希望管理员能够添加另一个 detail_name 和 detail_desc,如果他们愿意的话。

我该如何实施?


慕虎7371278
浏览 97回答 2
2回答

LEATH

您可以为此目的使用外键。然后您的代码将与此类似:class Car(models.Model):    # some code hereclass 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 Cardetail_infos = car.details.all()  # now detail_infos include queryset of all DetailInfo instances, that connected to Car在django admin中,您可以添加details为内联(例如,请参见此链接)。例子# admin.pyfrom django.contrib import adminfrom .models import Car, DetailInfoclass 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]

烙印99

按照我更新的 TabularInline 的代码admin.pyclass DetailInfoInline(admin.TabularInline):    model = DetailInfoclass ShowCaseAdmin(admin.ModelAdmin):    inlines = [        DetailInfoInline,    ]models.pyclass DetailInfo(models.Model):    link = models.CharField(max_length=200)    showcase = models.ForeignKey(ShowCase, on_delete=models.CASCADE, related_name='details')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python