Home > database >  Django REST API get only auth user datas
Django REST API get only auth user datas

Time:07-05

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

@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)

CodePudding user response:

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.

  • Related