Dango Rest Framework:如果满足条件,则设置foreign_key

时间:2018-05-09 18:02:31

标签: django postgresql django-rest-framework

Hy,我正在编写Django Rest Framework API,我将尝试用2个表解释我的问题:

table1:

   id / user_id / album_name

table2

   id / user_id / table1_id / song_name
    两个表中的
  • user_id列用于存储创建内容的用户的ID
  • id和user_id在模型定义中具有unique_together条件
  • table2有很多歌曲,每首歌曲可以来自一张专辑(table1)

现在,在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_keyuser_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)

1 个答案:

答案 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"),因为它永远不会发生(idPK因此,它永远不会重复{{1} }和id也) 4.如果我没错,' SongList'视图应包含user属性,或覆盖queryset方法。否则会引发get_queryset()异常