Correct Django models relationship
Preface: I have two models (Product
and UserProfile
) and I would to implement a mine comments system. The comment is related to an object, Product
or UserProfile
.
class Product(models.Model):
name = models.CharField(max_length = 40)
comments = models.ManyToMany(Comment)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
comments = models.ManyToMany(Comment)
class Comment(models.Model):
text = models.TextField()
author = models.ForeignKey(User)
timestamp = models.DateTimeField(auto_now_add = True)
Is it correct the logic under these models? I'm doubtful, because this way means a Product
can has many comments (and it's correct) but also a C开发者_运维知识库omment
can has many products (I don't think it's correct).
It isn't?
Your comment should have have a ForeignKey to the UserProfile or Product i.e. A single comment can only belong to a single product or user profile, but a user profile/product can have many different comments
def Comment(models.Model):
profile = models.ForeignKey(UserProfile)
product = models.ForeignKey(Profile)
Obviously this isn't ideal as there are two relationships you need to manage, and sometimes you will only want to use one etc.
To get over this, you can use a Generic Foreign Key:
https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations
this allows you to link a comment to any type of content (products, user profiles and more) without having to specify the models up front
def Comment(models.Model):
...
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
精彩评论