1

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?

Jan
  • 42,290
  • 8
  • 54
  • 79

1 Answers1

1

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')
Shang Wang
  • 24,909
  • 20
  • 73
  • 94
  • Brilliant, thanks (+1). I wasn't aware that you can do field lookups in the `values()` function as well. Will accept your answer shortly and love `Django` (was more of a `PHP` guy). – Jan Apr 20 '16 at 18:23
  • Short follow-up: Now the output looks something like `"userid__access_token": 'test1234'`, can I get rid of the `userid__` prefix? – Jan Apr 20 '16 at 18:33
  • 1
    That would be this question: http://stackoverflow.com/questions/10598940/django-rename-items-in-values. You could just use `values_list` if you only want one or two values, right? It would give you a list of tuples basically. – Shang Wang Apr 20 '16 at 18:34
  • Thanks again, will look into it! – Jan Apr 20 '16 at 18:40
  • @ShangWang what if no row is found for userid__userid? Is there a possible to return null value? – Soul Nov 08 '21 at 09:52