python根据id取值,Django - 通过相关字段的ID获取对象

在Django中,当`Zomg`模型的`foo`和`bar`字段构成复合键时,直接使用`get()`方法无法通过`foo_id`和`bar_id`获取记录。解决方法是使用`foo__id`和`bar__id`,如`z = models.Zomg.objects.get(foo__id=1, bar__id=1)`,这将避免额外的数据库查询,提高效率。
摘要由CSDN通过智能技术生成

Let's assume we have following models:

from django.db import models

class Foo(models.Model):

name = models.CharField(max_length=50)

class Bar(models.Model):

name = models.CharField(max_length=50)

class Zomg(models.Model):

foo = models.ForeignKey(Foo)

bar = models.ForeignKey(Bar)

In Zomg model foo and bar fields serve as composite key, that is, for any pair of (foo, bar) there is only one Zomg object.

In my project I need to update thousands of Zomg records from time to time, so efficiency of finding records is important. The problem is that I cannot just pass foo_id and bar_id to Zomg.objects.get() method:

>>> z = models.Zomg.objects.get(foo_id=1, bar_id=1)

Traceback (most recent call last):

File "", line 1, in

File "/usr/lib/python2.7/site-packages/django/db/models/manager.py", line 132, in get

return self.get_query_set().get(*args, **kwargs)

File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 341, in get

clone = self.filter(*args, **kwargs)

File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 550, in filter

return self._filter_or_exclude(False, *args, **kwargs)

File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 568, in _filter_or_exclude

clone.query.add_q(Q(*args, **kwargs))

File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1194, in add_q

can_reuse=used_aliases, force_having=force_having)

File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1069, in add_filter

negate=negate, process_extras=process_extras)

File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1260, in setup_joins

"Choices are: %s" % (name, ", ".join(names)))

FieldError: Cannot resolve keyword 'foo_id' into field. Choices are: bar, foo, id

However, when the object is instantiated foo_id and bar_id are pretty much accessible:

>>> z.foo_id

1

>>> z.bar_id

1

Now I'm forced to get Foo and Bar objects first and then use them to get the required Zomg object, making two unnecessary database queries:

>>> f = models.Foo.objects.get(id=1)

>>> b = models.Bar.objects.get(id=1)

>>> z = models.Zomg.objects.get(foo=f, bar=b)

So the question is, how can I get Zomg object by its related fields' IDs?

解决方案

Try this:

z = models.Zomg.objects.get(foo__id=1, bar__id=1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值