Jan Jan - 2 years ago 133
Python Question

Join two models in Django filter

I might be stupid for not finding the right keywords to look for, but here's the actual problem:

I'm trying to select database values by joining two different models in


Consider the following

class Token(models.Model):
userid = models.TextField()
access_token = models.TextField()
refresh_token = models.TextField(default='None', null=True)

class File(models.Model):
userid = models.ForeignKey(Token, on_delete=models.CASCADE)
name = models.TextField()
link = models.TextField()
size = models.BigIntegerField()

I'd now like to have all files from
with their corresponding

I tried to do the following:

data = File.objects.filter(name__startswith='Dummystring')

How to obtain the access_token in this scenario?

Answer Source

Use values or values_list to join the tables and get the values. Use __ to do field lookups:

data = File.objects.filter(name__startswith='Dummystring') \
                   .values_list('userid__access_token', 'userid__userid')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download