Jan Jan - 7 months ago 12
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

Django
.

Consider the following
models.py
:

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
File
with their corresponding
access_token
and
userid
.

I tried to do the following:

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


How to obtain the access_token in this scenario?

Answer

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')
Comments