Django模型主键成对 [英] Django model primary key as a pair
问题描述
我正在尝试开发一个应用程序,用户可以登录该应用程序并可以将歌曲添加到他们的收藏夹列表中。我正在为此定义M2M关系。
I am trying to make an app where users will login to their profile and can add songs to their favorite list. I am defining a M2M relationship for this.
我的问题是怎么说(歌曲,歌手)的组合是唯一的?我搜索了
,发现有可能通过unique_together。
My question is how to say combination of (song, singer) is unique? I searched and found that it may be possible through unique_together. Is this the correct way of setting this?
models.py:
models.py:
from django.contrib.auth.models import User
class Singer(models.Model):
name = models.CharField(max_length=500, unique=True)
def __str__(self):
return self.name
class Song(models.Model):
id = models.AutoField(primary_key=False)
singer = models.ForeignKey(Singer, on_delete=models.CASCADE, related_name='song')
name = models.CharField(max_length=500)
Class Meta:
unique_together = (singer, id)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
songs = models.ManyToManyField(Song, related_name='profile')
def __str__(self):
return self.user.username
请随时纠正我的模型.py,
Please feel free to correct my models.py, if you think the relationship is not correct.
谢谢,
推荐答案
我将使用默认的主键(自动字段),并使用元类属性unique_together
I would use a default primary key (auto field), and use the meta class property, unique_together
class Song(models.Model):
singer = models.ForeignKey(Singer, on_delete=models.CASCADE, related_name='song')
name = models.CharField(max_length=500)
class Meta:
unique_together = (("singer", "name"),)
它将充当代理主键列。
这篇关于Django模型主键成对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!