Aras121
Aras121

Reputation: 91

Django : Related Field got invalid lookup: user

I want to find practice data based on the user primary key. So when I open the url: localhost:8080/api/practice-filter?user=1 it will output all practice data based on the user with id 1.

model.py

class Practice(models.Model):
    practice_id = models.BigAutoField(primary_key=True)
    user = models.ForeignKey('User', models.DO_NOTHING, default=None)
    score = models.SmallIntegerField(null=True)

    class Meta:
        managed = True
        db_table = 'practice'

    def __str__(self):
        return str(self.practice_id)

class User(models.Model):
    user_id = models.BigAutoField(primary_key=True)
    fullname = models.CharField(max_length=50)
    email = models.CharField(max_length=100)
    password = models.TextField()

    class Meta:
        managed = True
        db_table = 'user'

    def __str__(self):
        return self.fullname

view.py

@api_view(['GET'])
def practice_filter(request):
    if request.method == 'GET':
        exercises = Practice.objects.all()
        
        user = request.GET.get('user', None)
        if user is not None:
            practice_filtered = exercises.filter(user__user__icontains=user)

        exercises_serializer = PracticeSerializer(practice_filtered, many=True)
        return JsonResponse(exercises_serializer.data, safe=False)

But when i run the above code i get an error :

Related Field got invalid lookup: user

How to solve this error? I do not know what to do. I'm still a beginner and need a lot of guidance. Please help. Thank you.

Upvotes: 0

Views: 286

Answers (1)

Mojtaba Arezoomand
Mojtaba Arezoomand

Reputation: 2380

You can go through foreign key fields with __.

but there is no field called user in User Model.

If you want to filter by user's fullname you can do this:

 practice_filtered = exercises.filter(user__fullname__icontains=user)

Upvotes: 2

Related Questions