Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django REST API get only auth user datas

I am new Django, I try make REST API. Now face one issue. I created 2 models Account & Transaction

class Account(models.Model):
    id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False)
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    account_name = models.CharField(max_length=100)

Account have ForeignKey with user model

class Transaction(models.Model):
    id = models.UUIDField(default=uuid.uuid4(),primary_key=True,editable=False)
    account = models.ForeignKey(Account,on_delete=models.CASCADE,related_name='account')
    transaction_no = models.CharField(default=str(uuid.uuid4())[:8],max_length=100)

Transaction have ForeignKey with Account model. then get JWT token & pass on API. In view.py I filtered by requested user

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def getAccount(request,pk):
    account = Account.objects.filter(user=request.user).get(id=pk)
    serializer = AccountSerializer(account, many=False)
    return Response(serializer.data)

now how will filter Transaction only by auth User

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def getTransactions(request,account_id):
    transactions = Transaction.objects.filter(account=account_id)
    serializer = TransactionSerializer(transactions, many=True)
    return Response(serializer.data)

>Solution :

You filter with:

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def getTransactions(request):
    transactions = Transaction.objects.filter(account__user=request.user)
    serializer = TransactionSerializer(transactions, many=True)
    return Response(serializer.data)

Here we thus retrieve Transactions for which the account refers to an Account object with request.user as user.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading