[Fixed]-Django – create a model that lets you insert multiple values for the same field?

23👍

Create a Review model which holds the review text and has a ForeignKey to Book

class Book(models.Model):
   title = models.CharField()

class Review(models.Model):
   book = models.ForeignKey(Book, related_name='reviews')
   review = models.TextField()

…then register the appropriate type of InlineModelAdmin to edit all the related reviews on the Book’s page in the admin. I’d suggest using a StackedInline in this case:

class ReviewInline(admin.StackedInline):
    model = Review

class BookAdmin(admin.ModelAdmin):
    inlines = [
        ReviewInline,
    ]

The documentation has an example of almost this exact scenario, except for multiple authors instead of multiple reviews:

0👍

Another option since Django 3.1. could be creating a JSON field and storing multiple values in a key value pair. Although it may not be suitable for all cases but for some that came to this topic it could work. Reference to Django docs https://docs.djangoproject.com/en/3.2/ref/models/fields/#jsonfield

Leave a comment