Keyinator
Keyinator

Reputation: 121

Django model allow multiple

So I want to create a model, let's say "Cars" I want to implement the field detail_name and detail_desc

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

But I want an admin to be able to add another detail_name and detail_desc if they wish to.

How can I implement that?

Upvotes: 0

Views: 134

Answers (2)

Keyinator
Keyinator

Reputation: 121

Thanks a lot to @Yevhenii M. for his help. Without him I wouldn't have gotten this working. Following the code for my updated 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')

Upvotes: 0

Yevhenii M.
Yevhenii M.

Reputation: 827

You can use Foreign key for this purpose.

Then your code will be similar to this:

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)

Then you can see all details by:

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

In django admin you can add details as inlines (see this link for example).

Example

# 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]

Upvotes: 1

Related Questions