简体   繁体   English

python-Django模型查询

[英]python - Django model query

I've 2 models : 我有2个型号:

class A(models.Model):
    a_id = models.CharField(max_length = 255, primary_key = True)
    destination = models.CharField(max_length = 255)

class B(models.Model):
    a_id = models.ForeignKey('A', related_name = 'pptls')
    some_unique_value = models.CharField(max_length = 255, unique = True)

I want to get destination from A given the some_unique_value from B . 给定Bsome_unique_value ,我想从A获得目的地

This is how I'm currently doing:- 这是我目前正在做的事情:-

a_id = B.objects.get(some_unique_value = "something").a_id
destination = A.objects.get(a_id = a_id).destination

Though, it fetches me the results, but I want to convert this into single line query, something like joins in SQL. 虽然,它获取了结果,但我想将其转换为单行查询,类似于SQL中的联接。 How can I do it? 我该怎么做?

You use the double-underscore syntax to traverse relationships: 您使用双下划线语法遍历关系:

destination = A.objects.get(b__some_unique_value="something").destination

This is very well covered in the documentation on making queries . 有关查询的文档对此进行了很好的介绍。

(Also, please don't name your ForeignKeys "_id": it doesn't represent an ID, it represents an actual object of the other class. Django automatically appends "_id" to the underlying database field anyway.) (此外,请勿将您的ForeignKeys命名为“ _id”:它不表示ID,而是表示其他类的实际对象。Django始终会自动将“ _id”附加到基础数据库字段中。)

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

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