I'm using django-taggit and I came upon a problem when trying to filter across relationships.
Having the following models:
class Artist(models.Model):
tags = TaggableManager()
class Gig(models.Model):
artist = models.ManyToManyField(Artist)
What I would like to achieve is the get all gigs who's artist(s) have a specific tag.
I thought this would be easy and eagerly wrote:
Gig.objects.filter(artist__tags__name__in=["rock"])
Which gave me:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/jonas/.virtualenvs/wsw/lib/python2.7/site-packages/django/db/models/manager.py", line 141, in filter
return self.get_query_set().filter(*args, **kwargs)
File "/home/jonas/.virtualenvs/wsw/lib/python2.7/site-packages/django/db/models/query.py", line 550, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/jonas/.virtualenvs/wsw/lib/python2.7/site-packages/django/db/models/query.py", line 568, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/jonas/.virtualenvs/wsw/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1172, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/home/jonas/.virtualenvs/wsw/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1139, in add_filter
process_extras=False)
File "/home/jonas/.virtualenvs/wsw/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1060, in add_filter
negate=negate, process_extras=process_extras)
File "/home/jonas/.virtualenvs/wsw/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1238, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'tagged_items' into field. Choices are: artist, date, id, location, url
I managed to fix it by commenting out TaggableManager.extra_filters() in manage.py.
Take it with a grain of salt, because I have no idea what I may have broken by doing this.
Getting all Gigs for who's Artist's have a specific tag.
artists = Artist.objects.filter(tags__name__in=["rock"])
gigs = Gig.objects.filter(artist__in=artists)
Related
Hello everyone I am trying to get data from database but it give me error in case when I am trying to get single data from db as shown below
wahid = Webapp.objects.get(title="Ecommerce Website")
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 418, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1258, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1084, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "C:\Users\wahid\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py", line 1481, in names_to_path
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'title' into field. Choices are: created, demo_link, description, id, review, source_link, tags, tiltle, vote_ratio, vote_total
It will work only on getting all data from db as shown in image
There is a spelling mistake,
You have created field name "tiltle" in models, however you are trying to fetch "title" in your get query
Also, using get query might throw an error if there are more than one record that have title="Ecommerce Website"
for that you can use
Webapp.objects.filter(title="Ecommerce Website")
you should rename title field in your model, it seems you enter title field name to wrong dictation
'tiltle' must be 'title' in your model
I have the following three models:
class Region(models.Model):
code = models.IntegerField()
class ReportRequest(models.Model):
# a report can include many regions
regions = models.ManyToManyField(Region)
class Office(models.Model):
# an office belongs to one region
region = models.ForeignKey(Region)
basically, many reports can have many regions, and one region can have many offices.
How can I get all offices related to my report's regions in one query?
I can do this with two queries:
region_pks = reportrequest.regions.values_list('id', flat=True)
offices = Office.objects.filter(region_id__in=region_pks)
but I feel there must be a way to do this in just one query.
I know how to do this if this was a chain of objects connected by ForeignKeys, but ManyToManyField confuses me a bit.
update:
this way Office.objects.filter(region__in=reportrequest.regions) doesn't work.
reportrequest = ReportRequest.objects.first()
print(Office.objects.filter(region__in=reportrequest.regions).all())
Traceback (most recent call last):
File "/Users/9999/_projects/declarator/transparency/transparency/scripts/process_report_requests.py", line 22, in <module>
print(Office.objects.filter(region__in=reportrequest.regions).all())
File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/query.py", line 691, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/modeltranslation/manager.py", line 338, in _filter_or_exclude
return super(MultilingualQuerySet, self)._filter_or_exclude(negate, *args, **kwargs)
File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/query.py", line 709, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1287, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1314, in _add_q
current_negated=current_negated, connector=connector)
File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1142, in build_filter
value, lookups = self.prepare_lookup_value(value, lookups, can_reuse)
File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1047, in prepare_lookup_value
value = value()
File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/fields/related.py", line 839, in __call__
manager = getattr(self.model, kwargs.pop('manager'))
KeyError: u'manager'
This
offices = Office.objects.filter(region__in=reportrequest.regions.all())
I have a User model, each User can have many Post by this relateion:
class Post(models.Model):
...
user = models.ForeignKey('User', related_name='posts')
, and each post have a like_count (integer field), i want to get users (along their posts) that has more that n posts which is liked more that m times, i do:
User.objects.prefetch_related(Prefetch('posts', queryset=Post.objects.filter(like_count__gte=m), to_attr='top_posts')).annotate(top_post_count=Count('top_posts')).filter(top_post_count__gte=n)
but, i get:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 912, in annotate
clone.query.add_annotation(annotation, alias, is_summary=False)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/query.py", line 971, in add_annotation
summarize=is_summary)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/aggregates.py", line 19, in resolve_expression
c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/expressions.py", line 513, in resolve_expression
c.source_expressions[pos] = arg.resolve_expression(query, allow_joins, reuse, summarize, for_save)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/expressions.py", line 463, in resolve_expression
return query.resolve_ref(self.name, allow_joins, reuse, summarize)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/query.py", line 1462, in resolve_ref
self.get_initial_alias(), reuse)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/query.py", line 1402, in setup_joins
names, opts, allow_many, fail_on_missing=True)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/query.py", line 1327, in names_to_path
"Choices are: %s" % (name, ", ".join(available)))
django.core.exceptions.FieldError: Cannot resolve keyword 'top_posts' into field. Choices are: ...
The docs explain it's assigned to an attribute, named according to the to_attr parameter, on the QuerySet items.
I don't think that implies it's accessible as a model field to which a subsequent annotations can be chained.
You probably need to separate it into two steps.
Edit: The question has commented that that filters can be chained but annotations cannot.
I recently upgraded from Django 1.6 to Django 1.8. When I did, I found that I was no longer able to to do a lookup back through a foreign key relationship as described in:
https://docs.djangoproject.com/en/1.8/topics/db/queries/#lookups-that-span-relationships.
The system is set up so that there are two projects which use the same database. (Not my idea, but not something I would like to change right now.) The project where the models were initially created and migrated works just fine after the upgrade, but the other one does not. The models file for each is identical.
Models.py:
class Site(models.Model):
name = models.CharField(max_length=255)
class Meta:
app_label = 'project1'
class Page(models.Model):
title = models.CharField(max_length=255)
site = models.ForeignKey('Site')
class Meta:
app_label = 'project1'
Error traceback from the Django Shell:
>>> x = models.Site.objects.filter(page__id=1000)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 679, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 697, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1314, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1342, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1154, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1035, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/home/user_name/project2/venv/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1401, in names_to_path
"Choices are: %s" % (name, ", ".join(available)))
FieldError: Cannot resolve keyword 'page' into field. Choices are: name, id
In the first project, the same query works as expected:
>>> x = models.Site.objects.filter(page__id=1000)
[<Site: http://stackoverflow.com>]
What if you set a related_name on the `ForeignKey ?
class Page(models.Model):
site = models.ForeignKey('Site', related_name="pages") # Note the related_name here
I tried it on another project and it work as axpected:
>>> Site.objects.filter(pages__pk=42)
[<Site: http://stackoverflow.com>]
If you don't set a related_name, I think the default is <model>_set. So it should be page_set.
I am new to Django, don't know if this helps but I had same issue. In my case, it was typing error.
I had written this earlier:
Question.objects.filter(question_text_startswith='What')
In Django documentation, I noticed there should be 2 underscores before the lookup startswith:
Question.objects.filter(question_text__startswith='What')
I have a model which can be attached to to other models.
class Attachable(models.Model):
content_type = models.ForeignKey(ContentType)
object_pk = models.TextField()
content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
class Meta:
abstract = True
class Flag(Attachable):
user = models.ForeignKey(User)
flag = models.SlugField()
timestamp = models.DateTimeField()
I'm creating a generic relationship to this model in another model.
flags = generic.GenericRelation(Flag)
I try to get objects from this generic relation like so:
self.flags.all()
This results in the following exception:
>>> obj.flags.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 105, in all
return self.get_query_set()
File "/usr/local/lib/python2.6/dist-packages/django/contrib/contenttypes/generic.py", line 252, in get_query_set
return superclass.get_query_set(self).filter(**query)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 498, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 516, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1675, in add_q
can_reuse=used_aliases)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1569, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1737, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'object_id' into field. Choices are: content_type, flag, id, nestablecomment, object_pk, timestamp, user
>>> obj.flags.all(object_pk=obj.pk)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: all() got an unexpected keyword argument 'object_pk'
What have I done wrong?
You need to define object_id_field and content_type_field when creating GenericRelation:
flags = generic.GenericRelation(Flag, object_id_field="object_pk", content_type_field="content_type")