我的 django 中有这个表:
class User(models.Model):
username = models.CharField(max_length=40)
class Photo(models.Model):
publish_by = models.ForeignKey(User)
name = models.CharField(max_length=40)
desc = models.CharField(max_length=40)
用户可以发布照片,他们可以喜欢照片。但是我不知道如何在照片中写类似,我应该使用一对多还是多对多?
以及如何获得喜欢照片的用户。
感谢帮助 。
更新
最后我决定使用多对多和直通模型,因为我也想记录时间。我选择的模型是这些
class User(models.Model):
username = models.CharField(max_length=40)
class Photo(Model):
author = models.ForeignKey(User, related_name='%(class)ss')
publish_time = models.DateTimeField(default=datetime.datetime.now)
liked_by = models.ManyToManyField(User, related_name="likes",through='PhotoLike',)
def like(self, user):
liked, created = PhotoLike.objects.get_or_create(photo=self,user=user)
return liked
def save(self, *args, **kwargs):
super(Photo, self).save(*args, **kwargs)
class Meta:
app_label = 'meinv'
class PhotoLike(models.Model):
user = models.ForeignKey(User)
photo = models.ForeignKey(Photo)
like_time = models.DateTimeField(default=datetime.datetime.now)
class Meta:
app_label = 'meinv'