django - 创建一个可以为同一个字段插入多个值的模型? [英] django - create a model that lets you insert multiple values for the same field?

查看:1484
本文介绍了django - 创建一个可以为同一个字段插入多个值的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我想做一些在我心中应该非常简单的事情,但是我可能会丢失一些SQL或django管理员的知识。
说我有一个简单的模型,如

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

和我希望管理员网站中的评论字段有一点加号,可以向模板实例添加更多评论,以便模板遍历它们。



我知道我可以为评论创建一个m2m字段,它会给我这样的,但我宁愿那些额外的评论可以从同一页面填写没有弹出窗口(对于我无奈的用户,我希望将它保持为WSIWYG,因为这些文本框将是tinyMCE的),我想知道是否真的有必要为文本框创建一个额外的模型

解决方案

创建一个审查模型,其中包含审阅文本,并具有 ForeignKey to Book ...

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

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

...然后注册相应的类型的 InlineModelAdmin 可以在管理员的书页上编辑所有相关评论。在这种情况下,我建议使用 StackedInline

  class ReviewInline (admin.StackedInline):
model =评论

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

文档中有几个这个确切情况的例子,除了多个作者,而不是多个评论:




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

解决方案

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:

这篇关于django - 创建一个可以为同一个字段插入多个值的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆