'filter a request in django serializer with the current logged-in user
Help please,
So, I am making a request with a serializer and what I need is to filter the response by current logged-in user. I was thinking about doing the request using serializerMethodField but it's a read-only type so I could not do anything with it after. Specially this code line which is necessary for my form, because it will retrieve all wallet linked to the current user into a select field, won't work :
to = serializers.PrimaryKeyRelatedField(queryset=serializers.SerializerMethodField('get_user_wallets'))
I thought also about the way of castrate the return type that I will get from get_user_wallets method into something that I can use as a queryset. But it seems not easy to do it. Maybe someone has a better approach of doing what I want.
Bellow is the code :
class TransactionSerializer(serializers.HyperlinkedModelSerializer):
to = serializers.PrimaryKeyRelatedField(queryset=serializers.SerializerMethodField('get_user_wallets'))
class Meta:
model = Transaction
fields = ['amount', 'to']
def get_user_wallets(self, obj):
request = self.context.get('request', None)
if request:
wallet = Wallet.objects.filter(user_id=request.user.pk)
return wallet
Thank you for your answers and suggestions.
My model is this one
class Transaction(models.Model):
wallet_id = models.ForeignKey(Wallet, on_delete=models.CASCADE)
transaction_type_id = models.ForeignKey(TransactionType, on_delete=models.CASCADE)
date = models.DateField(auto_now=True)
to = models.ForeignKey(Wallet, on_delete=models.CASCADE, related_name="send_to", verbose_name='Send to')
description = models.TextField()
amount = models.FloatField(blank=False, null=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
