简体   繁体   English

在 Django 过滤器中加入两个模型

[英]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 .我试图通过在Django加入两个不同的模型来选择数据库值。
Consider the following models.py :考虑以下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 .我现在想让File所有文件都带有相应的access_tokenuserid
I tried to do the following:我尝试执行以下操作:

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

How to obtain the access_token in this scenario?这种场景下如何获取access_token?

Use values or values_list to join the tables and get the values.使用valuesvalues_list连接表并获取值。 Use __ to do field lookups :使用__进行字段查找

data = File.objects.filter(name__startswith='Dummystring') \
                   .values_list('userid__access_token', 'userid__userid')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM