简体   繁体   中英

DRF Exclude from queryset

I'm trying to exclude ids from one model from foreignkey of another model. So i have a User model with ManyToMany going through Vote model. For now i tried many times in my ModelViewSet by .filter and .exclude and nothing working. (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.

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)

now the fromusers of vote model are excluded from User model

Try this in your 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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