Django模型继承(有没有办法组合两个不同的模型)

时间:2013-08-14 06:24:45

标签: python django

对不起标题中的混淆。

现在,我有两个继承BaseComment模型的Comment模型(QuestionComment和AnswerComment)。我不得不这样做,因为每个Comment模型都涉及两个不同的对象(分别是问答)。但是,我想知道是否有办法将这两个模型合二为一,而不必制作两个不同的评论模型。

由于我对不同的对象有两种不同的注释模型,我必须编写大量重复的模板,视图等。

任何想法:(((???

谢谢!

models.py

class BaseComment(models.Model):
    comment_author = models.ForeignKey(MyUser, related_name='written_comments')
    comment_content = models.CharField(max_length=500)
    comment_date = models.DateTimeField(auto_now_add=True)
    rating = models.IntegerField(default=0)

    class Meta:
        abstract = True

class QuestionComment(BaseComment):
    question = models.ForeignKey(Question, related_name='comments')

class AnswerComment(BaseComment):
    answer = models.ForeignKey(Answer, related_name='comments')

1 个答案:

答案 0 :(得分:7)

您可以使用generic relation执行此操作(更具体地说,是“Generic Foreign Key”)

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Comment(models.Model):
    comment_author = models.ForeignKey(MyUser, related_name='written_comments')
    comment_content = models.CharField(max_length=500)
    comment_date = models.DateTimeField(auto_now_add=True)
    rating = models.IntegerField(default=0)

    # These allow you to relate this comment instance to any type of object
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')


question = Question(...)
question.save()
answer = Answer(...)
answer.save()

q_comment = Comment(content_object=question, comment_author=..., ...)
q_comment.save()

a_comment = Comment(content_object=answer, comment_autho=..., ...)
a_comment.save()

q_comment.content_object  # Is the instance of the question
a_comment.content_object  # Is the instance of the answer