Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
994 views
in Technique[技术] by (71.8m points)

django - create a model that lets you insert multiple values for the same field?

Ok I'm trying to do something which should be very simple in my mind but I am probably missing some SQL or django admin knowledge to get to it. Say I have a simple model such as

class Book(models.Model):
    title = models.CharField(max_length = 50)
    review = models.TextField()

and I want the 'review' field in the admin site to have a little plus sign to add more reviews to the same model instance for the template to iterate through them.

I know I could create a m2m field for the reviews and it would give me just that, but I would rather like that those extra reviews could be filled from the same page without popups (for my helpless users i would like to keep it as WSIWYG as possible, since those textfields will be tinyMCE powered), and I wonder if it's really necessary to create an extra model just for a textfield

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...