Django - getting object by its related fields'

2019-05-31 11:28发布

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 "<console>", line 1, in <module>
  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?

1条回答
老娘就宠你
2楼-- · 2019-05-31 12:05

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

查看更多
登录 后发表回答