Search code examples
djangoforeign-keysmodels

Django two parameter filter query with foreign key


My Django models look like this:

class User(models.Model):
    userid = models.CharField(max_length=26,unique=True)
    #some more fields that are currently not relevant

class Followers(models.Model):
    user = models.ForeignKey('User',related_name='usr')
    coins = models.IntegerField()
    followers = models.CharField(max_length=26, null=True, blank=True)

I would now like to make a filter query in my Followers table selecting every entry where users have ID x and followers have ID y (I expect to get one result from the query).

To visualize what I have tried and know won't work is this:

queryfilter = Followers.object.filter(followers=fid, user=uid)

and this:

queryfilter = Followers.object.filter(followers=fid, user__userid=uid)

In the end I would like to access the coins:

c = queryfilter.coins

It may be possible that I cannot do it with one single query and need two, since I am trying to do a filter query with two tables involved.


Solution

  • Firstly, I have modified your 'Followers' model (for naming convention). models.py

    class Follower(models.Model):
        user = models.ForeignKey('User', related_name='followers')
        coins = models.IntegerField()
        key = models.CharField(max_length=26, null=True, blank=True)
    

    Your queryset should be ..

    views.py

    #coins
    coins = Follower.objects.filter(key=fid, user__userid=uid).get().coins