1

Sorry for the confusion in the title.

Now, I have two Comment models (QuestionComment and AnswerComment) that inherit the BaseComment model. I had to do this because each Comment model relates to two different objects (Question and Answer, respectively). However, I was wondering if there's a way to combine these two models into just one, without having to make two different comment models.

Since I have two different comment models for different objects, I have to write numerous duplicate templates , views, and etc.

Any ideas :(((???

Thanks!!

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')
4

1 回答 1

8

您可以使用通用关系来执行此操作(更具体地说,是“通用外键”)

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
于 2013-08-14T06:36:06.890 回答