简体   繁体   English

DRF从查询集中排除

[英]DRF Exclude from queryset

I'm trying to exclude ids from one model from foreignkey of another model. 我正在尝试从另一个模型的外键中排除一个模型的ID。 So i have a User model with ManyToMany going through Vote model. 所以我有一个通过ManytoMany进行投票模型的User模型。 For now i tried many times in my ModelViewSet by .filter and .exclude and nothing working. 目前,我在我的ModelViewSet中尝试了.filter和.exclude多次,但没有任何效果。 (For sure i'm doing it bad.) From User.vote i'm getting ids of voted users, and i want them to be excluded from to_user, so user logged in can't vote twice the same person, and himself. (确保我做得不好。)从User.vote我获得了已投票用户的ID,并且我希望将它们从to_user中排除,因此登录的用户不能对同一个人和他自己进行两次投票。

class User(AbstractUser):
... some code.

    vote = models.ManyToManyField('self', through=Vote,
                                           symmetrical=False,
                                           related_name='related_to+')

class Vote(models.Model):

from_user = models.ForeignKey(User, related_name='from_user', on_delete=models.CASCADE)
to_user = models.ForeignKey(User, related_name='to_user', on_delete=models.CASCADE)
status = models.IntegerField(choices=VOTE_STATUSES)

and serializer: 和序列化器:

class UserVoteSerializer(serializers.ModelSerializer):
    from_user = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserDefault())

    class Meta:
        model = UserVote
        fields = ('from_user', 'to_user', 'status')

in your views add this vote_from_user_ids = Vote.objects.values('from_user__id') now exclude vote objects from User by using users = User.objects.exclude(id__in = vote_from_user_ids) 在您的视图中添加此vote_from_user_ids = Vote.objects.values('from_user__id')现在通过使用users = User.objects.exclude(id__in = voice_from_user_ids)从User排除投票对象

now the fromusers of vote model are excluded from User model 现在,投票模型的fromusers已从User模型中排除

Try this in your views.py : 在您的views.py尝试一下:

from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
    serializer_class = UserVoteSerializer

    def get_queryset(self):
        return User.objects.exclude(id__in=Vote.objects.values_list('from_user__pk', flat=True).order_by('from_user__pk')))

It excludes all users whose ids exist in the from_user field of the Vote model, ie the users that have already voted, and returns the users that have not yet made a vote. 它排除了ID在Vote模型的from_user字段中存在的所有用户(即,已经投票的用户),并返回尚未投票的用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM