Django缩短保存到ForeignKeyField的查询

时间:2019-07-02 09:16:12

标签: django

我有2个模型OwnersRelationships

所有者

class Owner(models.Model):
    id = models.BigAutoField(primary_key=True)
    nickname = models.CharField(max_length=20, unique=True)

关系

class Relationships(models.Model):
    id = models.BigAutoField(primary_key=True)
    owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='relationship_owner')
    target_owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='relationship_target_owner')

要向Relationships添加行,我在下面的查询中使用了

owner1 = Owner.objects.filter(nickname='hide').first()
owner2 = Owner.objects.filter(nickname='john').first()
Relationships.objects.create(owner=owner1, target_owner=owner2)

这很清楚。但是当我检查django-debug-toolbar时,它查询了3次数据库。

  1. 从所有者表中获取nickname=hide

  2. 从所有者表中获取nickname=john

  3. hidejohn插入关系表。

我想知道,这是一种通用方法吗?

或者,执行上述查询是否有任何清晰的方法?

谢谢!

3 个答案:

答案 0 :(得分:0)

由于您与该模型具有<a class="button case-readmore" href="#"> Read Case <span class="button-bg"></span> </a>关系,因此可以使用以下方法:

ForeignKey

答案 1 :(得分:0)

尝试使用subqueries

from django.db.models import Subquery

owner1 = Owner.objects.get(nickname='hide')
owner2 = Owner.objects.get(nickname='john')

Relationships.objects.create(
    owner=Subquery(owner1)),
    target_owner=Subquery(owner2)
)

答案 2 :(得分:0)

如果将for(auto p : mep){ vector<int> temp; auto s = p->second; for(auto k : s){ auto ss = k->second; for(auto it : ss) temp.push_back(it); } result.push_back(temp); } 字段转换为nickname的主键,则使用to_field,则可以这样使用它:

Owner