简体   繁体   中英

Django Model Inheritance (is there a way to combine two different models)

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

You can use a generic relation to do this (more specifically, a ' 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM