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

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

问题描述

好的,我正在尝试做一些我认为应该非常简单的事情,但我可能缺少一些 SQL 或 django 管理知识来实现​​它.假设我有一个简单的模型,例如

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.

我知道我可以为评论创建一个 m2m 字段,它会给我这样的信息,但我更希望这些额外的评论可以在没有弹出窗口的情况下从同一页面填写(对于我无助的用户,我想保留它尽可能 WSIWYG,因为这些文本字段将由 tinyMCE 驱动),我想知道是否真的有必要为文本字段创建一个额外的模型

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

推荐答案

创建一个 Review 模型,该模型保存评论文本并有一个 ForeignKeyBook...

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()

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

...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天全站免登陆