动态地将字段添加到Django中的ModelForm

时间:2014-07-09 09:14:10

标签: django

我有几个型号:产品,评论和评论。产品有评论,评论有评论。我编写了如下代码:

class Comment(models.Model):
    author = models.CharField(max_length=50)
    content = models.TextField(max_length = 200)
    date = models.DateTimeField(auto_now_add=True, blank = True)

    def __unicode__(self):
        return '%s on %s' % (self.author, self.date)

class Review(models.Model):
    stars = models.FloatField()
    author = models.CharField(max_length = 50)
    title = models.CharField(max_length = 50)
    description = models.TextField(max_length = 500)
    date = models.DateTimeField(auto_now_add = True, blank = True)
    video = models.FileField(upload_to='upload', null = True, blank = True)
    image = models.FileField(upload_to='upload', null = True, blank = True)
    comments = models.ManyToManyField(Comment)

    def __unicode__(self):
        return '%s by %s' % (self.author, self.title)

class Product(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField(max_length = 500)
    image = models.FileField(upload_to='upload', null = True, blank = True)
    reviews = models.ManyToManyField(Review)

    def __unicode__(self):
        return '%s' % (self.name)

同样,我有基于模型的ModelForms,如下所示:

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ['author']
        labels = {
            'content': _('Comment:'),
        }

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        exclude = ['reviews']

class ReviewForm(forms.ModelForm):
    class Meta:
        model = Review
        exclude = ['author', 'comments']

直到这里,一切都很好。现在,我希望能够动态地向产品添加问题。因此,当管理员创建新产品时,他将能够向其添加特定于产品的问题(例如,产品的颜色等)(他想要多少问题 - 动态)。然后,当用户查看产品时,他会看到管理员提出的产品特定问题,并且他将能够回答这些问题。

所以,我的主要问题是: 一个。如何动态地将字段添加到数据库模型? 湾如何在评论中处理这些问题?一个产品可能会有多个评论,每个评论由不同的人进行,每个评论都应显示这些产品特定的问题。

谢谢!

1 个答案:

答案 0 :(得分:1)

为了给你一个快速举例说明我的评论(用记事本完成,也许有拼写错误):

class Comment(models.Model):
    pass

class Review(models.Model):
    comments = models.ManyToManyField(Comment)

class Product(models.Model):
    reviews = models.ManyToManyField(Review)

class Question(models.Model):.
    content = models.TextField(max_length = 500)
    product = models.ForeignKey(Product)

class QuestionAnswer(models.Model):
    content = models.TextField(max_length = 500)
    review = models.ForeignKey(Review)
    question = models.ForeignKey(Question)