Hy,我正在编写Django Rest Framework API,我将尝试用2个表解释我的问题:
table1:
id / user_id / album_name
table2
id / user_id / table1_id / song_name
现在,在table2
中创建新歌时,我想设置foreign_key
,这将指向album
中已经命名为table1
但仅} album
由尝试创建新歌的同一用户创建
if user_id from table1 and user_id from current user are the same
Else there should be no foreign_key set for that song.
我正在尝试在此条件下设置foreign_key
以保持租户数据隔离,以便来自table2
的歌曲不能错误地连接到来自table1
的专辑,如果相同的用户没有&#39 ; t创建专辑,然后创建歌曲。
我在为活跃用户设置foreign_key
列user_id
时没有任何问题,但我仍然坚持这一点。我也没有在文档中找到类似的例子。提前感谢您的帮助。
models.py
class Album(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
name = models.CharField(unique=True, max_length=100)
class Meta:
unique_together = ("id", "user")
class Song(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
name = models.CharField(default='', max_length=50)
album = models.ForeignKey(Album, null=True, blank=True, on_delete=models.PROTECT)
class Meta:
unique_together = ("id", "user")
serializers.py
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
model = Album
fields = ('name',)
class SongSerializer(serializers.ModelSerializer):
album = serializers.PrimaryKeyRelatedField(many=False, read_only=True)
class Meta:
model = Song
fields = ('name', 'album')
views.py
class SongList(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = SongSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)
答案 0 :(得分:0)
如下所示更改serializer.py
,
class SongSerializer(serializers.ModelSerializer):
class Meta:
model = Song
fields = ('name', 'album')
def create(self, validated_data):
if validated_data['album'].user == self.context.get('request').user:
album = validated_data.pop('album')
return Song.objects.create(**validated_data, album=album)
raise serializers.ValidationError("There is no album related to current user")
备注强>:
你应该在操作之前登录
2.您可以更改验证错误,如果需要,可以执行其他操作
3.你不必在模型中指定unique_together = ("id", "user")
,因为它永远不会发生(id
是PK
因此,它永远不会重复{{1} }和id
也)
4.如果我没错,' SongList'视图应包含user
属性,或覆盖queryset
方法。否则会引发get_queryset()
异常