Related field got invalid lookup icontains
Related field got invalid lookup icontains
Troubleshooting «Related Field has invalid lookup: icontains»
I have the following models in models.py :
While in the admin.py I have the following:
But when I try to make a search in the admin page in the ListinoTraduttore table I have the following error:
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Have you tried adding the __fieldname on those Lingua references in the ListinoTraduttoreAdmin search_fields, like:
This is to (hopefully) simplify the answer.
Don’t filter on a ForeignKey field itself!
to this (notice TWO underscores)
name represents the field-name from the table that we have a ForeignKey relationship with.
Hope this helps
Use Django’s double underscore convention instead. docs foreignkeyfield__name
Make sure you are not adding any Foreignkey or ManyToManyField to your search_field directly.
Double underscore needed
This worked for me.
Search the field of the foreign key using my_related_object__first_attribute:
This error, mostly occurs when you try to filter using a ForeignKey. I think the error is in the search_filelds. Check it. search_fields = [‘traduttore__nome», «linguaDa», «linguaA»]. This two ForeignKey («linguaDa», «linguaA») are the problem. Remove them. I think this helps.
It works backwards, too. Whilst it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model.
Multiple search with django foreign key (Related Field got invalid lookup: icontains)
I understand that you can’t directly use icontains on a foreign key when searching but I haven’t found a solution yet.
Here is my search view in views.py (I have imported every model needed):
Here is my model in model.py:
Mainly, this is not working:
The error is Related Field got invalid lookup: icontains
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You thus filter with:
Note: Searching is usually done through a GET rquest, since that means the query is stored in the querystring and thus the URL. This makes it convenient to for example share the URL with the query to someone else, or bookmark the result. POST requests are usually used for state-changing actions, or for requests with sensitive data.
This problem is caused by Django’s inability to handle foreign keys with multiple values for a single field. The reason for this limitation is that Django doesn’t know how to resolve these conflicts, so it simply ignores them. In your case, since there are two fields in your model that match the search criteria, Django will ignore both of those results and display an empty list.
To fix this issue, we need to add a new attribute to our model called «icontains» which would contain the value of the other field. Then, we’ll set this attribute as a default value for the «author» field when querying from the database. Here is what your model should look like now:
With this change, the code will work properly.
django admin related Field got invalid lookup: icontains
I got these Models:
I have these Admin Objects:
The list_display works fine but the search always gives an error saying:
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Turns out the error is because of
«the_image» is a FilerImageField object, it causes the error.
It works when i turned it into:
Behind the scene
This is from Django documentation:
When somebody does a search in the admin search box, Django splits the search query into words and returns all objects that contain each of the words, case insensitive, where each word must be in at least one of search_fields.
Therefore, if you want to allow search, you probably want to add the field title instead, which I assumed is the name of the image. This way, people will be able to search image by their name.
Django admin panel search bar not work (Related Field got invalid lookup: icontains)
I have in models
and in the wallet app admin.py
the search bar has exist but when I search for any user I got this error
django.core.exceptions.FieldError: Related Field got invalid lookup: icontains
1 Answer 1
You need to give the field on the user model you want to search, for example:
Not the answer you’re looking for? Browse other questions tagged python django or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Устранение неполадок «Связанное поле имеет недопустимый поиск: icontains»
У меня есть следующие модели models.py :
Пока в admin.py наличии у меня следующее:
Но когда я пытаюсь выполнить поиск на странице администратора в ListinoTraduttore таблице, у меня возникает следующая ошибка:
Вы пробовали добавить __fieldname эти Lingua ссылки в ListinoTraduttoreAdmin search_fields, например:
Это должно (надеюсь) упростить ответ.
в (обратите внимание на ДВА подчеркивания)
name представляет имя поля из таблицы, с которой у нас есть отношения ForeinKey.
Надеюсь это поможет
Убедитесь, что вы не добавляете Foreignkey или ManyToManyField напрямую в search_field.
Вместо этого используйте соглашение Django о двойном подчеркивании. документы
Требуется двойное подчеркивание
Это сработало для меня.
Найдите поле внешнего ключа, используя my_related_object__first_attribute:
Эта ошибка чаще всего возникает при попытке выполнить фильтрацию с помощью ForeignKey. Думаю ошибка в search_filelds. Проверь это. search_fields = [‘traduttore__nome «,» linguaDa «,» linguaA «]. Проблема в этих двух ForeignKey (» linguaDa «,» linguaA «). Удалите их. Я думаю, это поможет.
Сбивает с толку то, что значение по умолчанию related_name (т.е. _set ) не совпадает со значением по умолчанию related_query_name (т.е. ), но если вы установите пользовательский related_name (или default_related_name через Meta параметры модели ), он также будет использоваться по умолчанию related_query_name (как указано в документации).
Related Field got invalid lookup
I have a Django3 project (my first) with a model named Product that has a m2m relationship with Location (ProductLocation). ProductLocations have a m2m relationship with Category through ProductLocationCategory). I am looking to pull all products that have ProductLocation.active = True and ProductLocation.active_last_run = False. To do so, I use the following code:
which I borrowed from the Django help docs. The Product, ProductLocation, and ProductLocationCategory are as follows:
The full(er) error I receive is as follows:
I have verified all the migrations have run, the fields are in the database, I have created multiple migrations adding and removing the field. If I only run:
then the view will complete as normal. I have searched through most of the similar questions here on SO to get where I am at now and most of the remaining topins are using something like:
I am sure I am missing something simple but I can’t see it. Thanks for all your help SO!
Added the Location model although I omitted the address fields as I didn’t think they were relevant.
To add, the general structure of the data is as follows:
A product can belong to multiple locations and each location can have that product in multiple categories (featured, etc..)
I am struggling to figure out the how to run queryset filter using «field__contains» on a SlugRelatedField. I have a simple Book model and a Tag model that looks as following:
Now in my BooksView, I want to be able to filter the queryset by meta_tags value. I’ve tried the following with «__contains» field lookup:
But I get the following error from django:
MyProject/venv/lib/python3.6/site-packages/django/db/models/sql/query.py», line 1076, in build_lookup raise FieldError(‘Related Field got invalid lookup: <>‘.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: contains
Which as I understand means that since «meta_tags» is not a regular array or Text field, the contains field lookup cannot be applied on that field.
What is the best way if so to filter the queryset in such case for meta_tags value?
1 Answer 1
A django expert I’ve consulted about this issue, suggested to try append the «slug_field» («__value» in this case) to «__contains» field lookup when used with external model.
It was not documented anywhere or even on django official documentation at https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#contains, so I had no way to know it works this way, but this solution actually works:
It actually makes sense when you look deeper at the MetaTag model, as «value» is the inner field of the meta_tags model:
The reason it was not so obvious to append __value at the first place is because meta_tags array (array of objects) is flattened using the SlugRelatedField serializer where only the slug_field is projected and the rest fields are omitted. So the final output of meta_tags array is flat:
But since serialization on django DRF is made on a late stage (after queryset is completed) the original field schema should be considered.
Hope this will save somebody’s headache someday.
TypeError: Related Field got invalid lookup: balance
I am trying to access a decorate from model. When I try to access this balance variable to generate a link, receiving all the accounts I get this error. I want to find all the accounts that has a balance of 0, so completed account.
1 Answer 1
balance is a property (computed in Python) but it has no counterpart in the database (no balance field) so you cannot filter on it (not with QuerySet filter method at least).
You can iterate on the queryset to do your own filtering (bad, can cause performance issues) You can also denormalize the balance (create a new field in the model) to store the result of balance, then do some filtering as you did.
Another option would be to create an sql query to get balance computed by your database on the fly, then filter on it.
TypeError: Related Field got invalid lookup: balance
I am trying to access a decorate from model. When I try to access this balance variable to generate a link, receiving all the accounts I get this error. I want to find all the accounts that has a balance of 0, so completed account.
1 Answer 1
balance is a property (computed in Python) but it has no counterpart in the database (no balance field) so you cannot filter on it (not with QuerySet filter method at least).
You can iterate on the queryset to do your own filtering (bad, can cause performance issues) You can also denormalize the balance (create a new field in the model) to store the result of balance, then do some filtering as you did.
Another option would be to create an sql query to get balance computed by your database on the fly, then filter on it.
Error searching in Django admin
Here is the relevant part of my code:
I got an TypeError instead:
What value should I set search_fields to?
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Check search_fields documentation, so as stated there
These fields should be some kind of text field, such as CharField or TextField. You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation:
So in your case
Also notice it doesn’t say you could use calculated property as you tried at first
Write your admin class like this
search fields must be like this identity__fieldname
Устранение неполадок «Связанное поле имеет недопустимый поиск: значки»
У меня есть следующие модели в models.py :
Хотя в admin.py У меня есть следующее:
Но когда я пытаюсь выполнить поиск на странице администратора в ListinoTraduttore стол у меня следующая ошибка:
9 ответы
Это (надеюсь) упростить ответ.
Не фильтруйте по полю ForeignKey!
к этому (обратите внимание на ДВА подчеркивания)
name представляет имя поля из таблицы, с которой у нас есть отношение ForeignKey.
Надеюсь это поможет
Вы пробовали добавить __fieldname на тех Lingua ссылки в ListinoTraduttoreAdmin search_fields, например:
ответ дан 15 апр.
Вместо этого используйте соглашение о двойном подчеркивании Django. Документы foreignkeyfield__name
Make sure you are not adding any Foreignkey or ManyToManyField to your search_field directly.
Требуется двойное подчеркивание
ответ дан 21 мая ’20, 22:05
Это работает для меня.
Найдите поле внешнего ключа, используя my_related_object__first_attribute:
ответ дан 11 мар ’20, в 14:03
Это работает и в обратном направлении. Хотя его можно настроить, по умолчанию вы ссылаетесь на «обратное» отношение при поиске, используя название модели строчными буквами.
ответ дан 28 окт ’20, 16:10
Эта ошибка в основном возникает при попытке фильтрации с помощью внешнего ключа. Я думаю, что ошибка в файле search_fileds. Проверь это. search_fields = [‘traduttore__nome», «linguaDa», «linguaA»]. Проблема заключается в этих двух ForeignKey («linguaDa», «linguaA»). Удалите их. Думаю, это поможет.
добавить в admin.py
ответ дан 01 авг.
это может быть странно
если вот так, с одинарными кавычками возникнет ошибка.
предоставление с двойными кавычками решит проблему
Issues
Context Navigation
#23351 closed Cleanup/optimization (duplicate)
Admin Search Field error for related lookup
Reported by: | Ezequiel Bertti | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.7 |
Severity: | Normal | Keywords: | |
Cc: | florent.pastor@…, zeraien | Triage Stage: | Unreviewed |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
I’m using Django Version 1.7c2 and I have these two models :
And this Admin Class:
And i’m getting this error
FieldError at /admin/app/subject/
Relation fields do not support nested lookups
on django\db\models\fields\related.py in get_lookup_constraint
raise exceptions.FieldError(‘Relation fields do not support nested lookups’)
Change History (4)
comment:1 follow-up: 3 Changed 8 years ago by Ramiro Morales
I can’t reproduce this with the information provided and using a simple setup containing only the code shown by the OP.
Reopne if you can post more details.
comment:2 Changed 8 years ago by Florent Pastor
The admin class is still the same :
When I try to search, I get this issue :
By the way, I run Django 1.6.5, I did not test my project under django 1.7.
comment:3 in reply to: 1 Changed 8 years ago by zeraien
Cc: | zeraien added |
---|---|
Resolution: | worksforme |
Severity: | Release blocker → Normal |
Status: | closed → new |
Type: | Uncategorized → Bug |
Version: | 1.7-rc-2 → 1.7 |
I can’t reproduce this with the information provided and using a simple setup containing only the code shown by the OP.
Reopne if you can post more details.
I discovered the problem seems to be related to this ticket: #23697
If using this: search_fields = (‘module__name’,) but name does not exist in the module model, this error is thrown.
Using django 1.7.3
comment:4 Changed 8 years ago by Simon Charette
Resolution: | → duplicate |
---|---|
Status: | new → closed |
Type: | Bug → Cleanup/optimization |
Thanks for the report but let’s keep this ticket closed by marking it as a duplicate instead and move all discussion to #23697.
The fix suggested by Tim on #23697 should prevent reports similar to this one which were probably caused by a simple typo in the field name.
Django filter related field using related model’s custom manager
How can I apply annotations and filters from a custom manager queryset when filtering via a related field? Here’s some code to demonstrate what I mean.
Manager and models
Attempting to filter the related field using the manager
If you try the above code you will get the following error:
TypeError: Related Field got invalid lookup: some_flag
To further clarify, essentially the same question was reported as a bug with no response on how to actually achieve this: https://code.djangoproject.com/ticket/26393.
I’m aware that this can be achieved by simply using the filter and annotation from the manager directly in the MyModel filter, however the point is to keep this DRY and ensure this behaviour is repeated everywhere this model is accessed (unless explicitly instructed not to).
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
How about running nested queries (or two queries, in case your backend is MySQL; performance).
The first to fetch the pk of the related OtherModel objects.
The second to filter the Model objects on the fetched pks.
I don’t think what you want is possible.
1) I think you are miss-understanding what annotations do.
Generating aggregates for each item in a QuerySet
The second way to generate summary values is to generate an independent summary for each object in a QuerySet. For example, if you are retrieving a list of books, you may want to know how many authors contributed to each book. Each Book has a many-to-many relationship with the Author; we want to summarize this relationship for each book in the QuerySet.
Per-object summaries can be generated using the annotate() clause. When an annotate() clause is specified, each object in the QuerySet will be annotated with the specified values.
The syntax for these annotations is identical to that used for the aggregate() clause. Each argument to annotate() describes an aggregate that is to be calculated.
So when you say:
which would be super slow and I’m not surprised they are not doing it.
Possible solution
don’t annotate your field, but add it as a regular field in your model.
django foreign key lookup aggregate data
I am making a tool inventory/tracking system. My current question is how can I gather the total number of tools that are currently checked out, and subtract that amount from the total quantity that I have of that tool. So that I can display a quantity on hand. So that a user can make sure that the tool is currently in the shop and is not checked out by someone borrowing it.
I was receiving this error: Related Field got invalid lookup: icontains I have removed the line of code in my view that is listed above that was causing the error: queryset = ToolCheckIn.objects.all().filter(ToolID_id__icontains=pk)
Not sure if I can achieve this from the ORM or if I will need to write some raw sql to achieve this. I am currently using a MYSQL DB.
Any thoughts or ideas would be appreciated.
1 Answer 1
Adding the important information from comments to the answer.
In your case the suitable contains query will be
If you would have made a contains query on say field Location of the model Tool then your query would have looked something like this
The foreign key is sort of a door to the model from where the foreign key or the relation is coming from and the double underscore is the path to the same.
I hope this clears it for you.
Though the interesting thing to note is that why the below didn’t work
Even the Docs don’t provide any information regarding how a foreign key is kept in the table. Whether it is formatted or hashed before storing so as to why the contains query gave an Related Field got invalid lookup: icontains error or whether Django doesn’t supports the contains lookup on foreign keys directly, only supporting the equality lookup i.e., assuming the foreign key to always be an integer type as the foreign key is the primary key of the model from where it comes, and by default, if you don’t provide any primary key, then Django makes its own primary key which of the int type. Hence, not covering the case when the primary key can be field of Char type, which brings with it the possibility of a contains lookup as contains won’t work on int type.
That’s what I think as I didn’t find much relevant info on the internet regarding the same.
How to search by related model field using django-extra-views?
I got Person object with foreign key to contact model. Contact has first_name field. Howe do I search by that first_name field? models:
Sorting works just fine but I’m no sure how to create GET search request. I tried http://
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Newer versions of django have a security feature which prevents lookups on related models. The workaround can be found on this question: Django: Filtering by %filter% not allowed
You cannot specify which of the fields will be searched in the query parameter of the URL. Your URL should look like this:
This will search in both contact__first_name and contact__last_name fields, since those are the fields specified by the *search_field* attribute of your view.
You can have a look at the get_queryset method of the SearchableListMixin class to see how the query is parsed and of the class handles both the query parameter and the search fields.
How to search by related model field using django-extra-views?
I got Person object with foreign key to contact model. Contact has first_name field. Howe do I search by that first_name field? models:
Sorting works just fine but I’m no sure how to create GET search request. I tried http://
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Newer versions of django have a security feature which prevents lookups on related models. The workaround can be found on this question: Django: Filtering by %filter% not allowed
You cannot specify which of the fields will be searched in the query parameter of the URL. Your URL should look like this:
This will search in both contact__first_name and contact__last_name fields, since those are the fields specified by the *search_field* attribute of your view.
You can have a look at the get_queryset method of the SearchableListMixin class to see how the query is parsed and of the class handles both the query parameter and the search fields.
Issues
Context Navigation
#2331 closed defect (invalid)
Related Field has invalid lookup: icontains
Reported by: | ian@… | Owned by: | Adrian Holovaty |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | |
Severity: | normal | Keywords: | |
Cc: | gmludo@… | Triage Stage: | Unreviewed |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by Malcolm Tredinnick )
just upgraded to the latest head, and found this.
I could have sworn it was working beforehand.
Change History (12)
comment:1 Changed 16 years ago by Malcolm Tredinnick
Could you provide an example of what you were doing to trigger this error, please. It is impossible to work it out just from the traceback. A model and a query against it that fails reliably would be nice. Thanks.
comment:2 Changed 16 years ago by Malcolm Tredinnick
OK, ignore my last comment, it was lazy. I looked at the code. Suspicion falls on [3246], but it looks like Russell was not expecting non-standard primary keys in there (maybe?). Are you seeing this on a model that has a custom primary key? If not, why on earth are we in that method?
I’m reluctant to go diving in here trying to fix edge cases whilst Adrian is doing his refactoring. The odds of a patch surviving are small. The whole query dissecting and processing phase is possibly open on his lab table with entrails all over the place.
comment:3 Changed 16 years ago by Ian@…
Hi.
It was actually an error on my part.. the field it was it is looking at is a generic relation similar to one in
http://svn.zyons.python-hosting.com/trunk/zilbo/common/forum/models.py
class Forum:: summary_tags
but the error looked weird and didn’t use to fail in such a way a week or two ago.
comment:4 Changed 16 years ago by Malcolm Tredinnick
I’m confused, then. Is this a bug in Django or just a confusing error?
comment:5 Changed 16 years ago by Chris Beaven
Closing as Ian stated it was an error on his part. Ian: If there’s still a problem with Django that needs to be fixed, please reopen.
comment:6 Changed 13 years ago by AntonBessonov
This error raised if use search_fields in admin.py. E.x:
Maybe must raise properly exception?
comment:7 Changed 11 years ago by Jeff Blaine
Easy pickings: | unset |
---|---|
Resolution: | invalid |
Status: | closed → reopened |
I’m getting this in 1.3, some 2 years later than the last comment above.
Same situation as above, using Admin. Any search results in the same error as this ticket:
comment:8 Changed 11 years ago by Jeff Blaine
Ignore me. I am an idiot. Fixed. Re-resolving as invalid.
How to search by related model field using django-extra-views?
I got Person object with foreign key to contact model. Contact has first_name field. Howe do I search by that first_name field? models:
Sorting works just fine but I’m no sure how to create GET search request. I tried http://
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Newer versions of django have a security feature which prevents lookups on related models. The workaround can be found on this question: Django: Filtering by %filter% not allowed
You cannot specify which of the fields will be searched in the query parameter of the URL. Your URL should look like this:
This will search in both contact__first_name and contact__last_name fields, since those are the fields specified by the *search_field* attribute of your view.
You can have a look at the get_queryset method of the SearchableListMixin class to see how the query is parsed and of the class handles both the query parameter and the search fields.
Searchable collumns #8
Comments
daviddutch commented Aug 13, 2013
I’m pretty new to django so hopefully everything I say will be correct.
If I add the primary key has a column text search will crash the app because pk__icontains is not a legal operation.
The simplest way I found to get around the problem is making the column not searchable. But this feature doesn’t seem to be supported in eztables.
I’ve modified the global_search method the following way:
Or is there another way of stoping the app from crashing with having the primary key (pk column) in the data?
The text was updated successfully, but these errors were encountered:
noirbizarre commented Aug 19, 2013
I will need some more details to implement the test case and the fix.
daviddutch commented Aug 20, 2013
I use Django 1.5.
To stop a column from being searchable from the client side you need to use the aoColumnDefs property like this:
On the server side I don’t do anything special:
The problem is having the primary key in the column. I need it to generate the buttons links on the client side.
Another nice fix would be to make it possible to search on the primary key as well without it crashing.
So when I don’t have my fix the error when searching is:
You should find a way to use a different operator than icontains on primary keys.
daviddutch commented Aug 20, 2013
Maybe as an example you can have a look at the php code here: http://datatables.net/development/server-side/php_mysql
They search only on the columns that are searchable.
thepapermen commented Oct 31, 2013
The issue seems legitimate and is reproducible on Django 1.6, but not in a way that original poster supposed.
Take a look at this model:
Let’s say we’ve got two tables, both have «aoColumns»: < "mData": 'related_item' >in their respective dataTable declaration:
It looks like eztables.views.DatatablesView.global_search sets criterions criterions = (Q(**<'%s__icontains' % field: term>) for field in self.get_db_fields()) which are not compatible with related fields.
Whether this behavior is to be considered a documentation issue or a genuine bug, is a good question.
How to dynamically provide lookup field name in Django query? [duplicate]
I want to look for a certain string in several fields of a Model in Django. Ideally, it would go something similar to:
Of course this won’t work, as «lookup» can’t be resolved into a field. Is there any other way to do this?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I would prefer to use the Q object for something like this.
I think there may be a better way to do this with the Django query system. Here’s how to do it your way.
Python allows you to pass dictionaries to be used as argument lists by prefixing them with **. With a spot of luck, you should be able to do something like this:
I like DialZ’s answer but for performance reasons you should build the query and then hit the database once instead of concatenating all the results into a list:
I havn’t done one of these in a while, but I’m pretty sure django will not actually hit the database at all in this code. It will only perform a query when you access the data contained in the records
Problems displaying and filtering Method and ReadOnly Fields #6
Comments
neighlyd commented May 15, 2018
It appears that the filter logic doesn’t have a way to deal with calculated fields (i.e. SerializerMethodField() or ReadOnlyField() ).
If I set the name: field in columns to a different field in the model, it will display the data. However, it is not searchable or filterable. Doing so returns the following error:
Related Field got invalid lookup: icontains
It seems that the way forward would be to provide a separate query param that stipulates what the filter field should be for a given column. However, I don’t think that Datatables has this functionality built in with how it formats url query params for server side processing.
Perhaps it would be possible to repurpose the columns[i][name] param for this purpose, but that seems hacky-af.
The text was updated successfully, but these errors were encountered:
Множественный поиск с внешним ключом django (Related Field got invalid lookup: icontains)
Я понимаю, что нельзя напрямую использовать иконки на внешнем ключе при поиске, но пока не нашел решения.
Вот мое представление поиска в файле views.py (я импортировал все необходимые модели):
Вот моя модель в model.py:
В основном, это не работает:
Ошибка Related Field got invalid lookup: icontains
Таким образом, вы фильтруете:
Примечание: Поиск обычно выполняется через запрос GET, поскольку это означает, что запрос хранится в строке запроса и, следовательно, в URL. Это делает удобным, например, передачу URL с запросом кому-то другому или добавление результата в закладки. POST-запросы обычно используются для действий, изменяющих состояние, или для запросов с чувствительными данными.
Эта проблема вызвана неспособностью Django обрабатывать внешние ключи с несколькими значениями для одного поля. Причина этого ограничения в том, что Django не знает, как разрешить эти конфликты, поэтому просто игнорирует их. В вашем случае, поскольку в вашей модели есть два поля, которые соответствуют критериям поиска, Django проигнорирует оба результата и отобразит пустой список.
Чтобы решить эту проблему, нам нужно добавить новый атрибут в нашу модель под названием «icontains», который будет содержать значение другого поля. Затем мы установим этот атрибут в качестве значения по умолчанию для поля «author» при запросе из базы данных. Вот как теперь должна выглядеть ваша модель:
После этого изменения код будет работать правильно.
How to dynamically provide lookup field name in Django query? [duplicate]
I want to look for a certain string in several fields of a Model in Django. Ideally, it would go something similar to:
Of course this won’t work, as «lookup» can’t be resolved into a field. Is there any other way to do this?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I would prefer to use the Q object for something like this.
I think there may be a better way to do this with the Django query system. Here’s how to do it your way.
Python allows you to pass dictionaries to be used as argument lists by prefixing them with **. With a spot of luck, you should be able to do something like this:
I like DialZ’s answer but for performance reasons you should build the query and then hit the database once instead of concatenating all the results into a list:
I havn’t done one of these in a while, but I’m pretty sure django will not actually hit the database at all in this code. It will only perform a query when you access the data contained in the records
In Django using fiter() then get() on queryset?
Can I combine the use of filter() and get() on querysets to return an object in a django view? I have the following view;
Items are all unique for city and store. I am currently trying to filter a queryset based on the two ForeignKey fields and then use get on a CharField but am getting an error message that the object does not exist. Am I approaching this incorrectly or is my syntax off somewhere? Thanks
1 Answer 1
If your related filter returns only 1 result, then you can use :
which filters the Item records and store them in a QuerySet, which has a list-lilke structure, then take the first element.
If you are sure to get a result, then you can use get instead of filter:
But if there exists no record which fits your filer criteria, then you get an error. So if you are not sure whether filtering will return a result or not, then use:
which ckecks the resulting queryset and takes the first result if exists any.
Solve django admin search error related fields has invalid lookup: icontains
When we trying to do search in Django admin, suddenly we caught by this error:
TypeError at /admin/myapp/myappfolder/
Related Field has invalid lookup: icontains
Then we should check that search_fields in DjangoAdmin should be on field rather on ForeignKey objects.
Eg :
class InsuranceAdmin(admin.ModelAdmin):
«»»Set Insurance Configuration in Admin page»»»
list_display = [«country», «subscription», «created», «modified»]
list_filter = («country», «subscription»)
search_fields = (‘country’, )
At this example, country is ForeignKey to Country models. When it comes to search_fields, it’s should be fields, so the correct version is :
class InsuranceAdmin(admin.ModelAdmin):
«»»Set Insurance Configuration in Admin page»»»
list_display = [«country», «subscription», «created», «modified»]
list_filter = («country», «subscription»)
search_fields = (‘country__name’, )
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Устранение неполадок «Связанное поле имеет недопустимый поиск: значки»
У меня есть следующие модели в models.py :
В то время как у admin.py меня есть следующее:
Но когда я пытаюсь сделать поиск на странице администратора в ListinoTraduttore таблице, я получаю следующую ошибку:
Вы пытались добавить __fieldname эти Lingua ссылки в ListinoTraduttoreAdmin search_fields, например:
Это (надеюсь) упростить ответ.
Не фильтруйте по полю ForeignKey!
к этому (обратите внимание на ДВА подчеркивания)
name представляет имя поля из таблицы, с которой у нас есть отношение ForeignKey.
Надеюсь это поможет
Вместо этого используйте соглашение о двойном подчеркивании Django. документы foreignkeyfield__name
Make sure you are not adding any Foreignkey or ManyToManyField to your search_field directly.
Требуется двойное подчеркивание
Это сработало для меня.
Найдите поле внешнего ключа, используя my_related_object__first_attribute:
Эта ошибка в основном возникает при попытке фильтрации с помощью внешнего ключа. Я думаю, что ошибка в файле search_fileds. Проверь это. search_fields = [‘traduttore__nome», «linguaDa», «linguaA»]. Проблема заключается в этих двух ForeignKey («linguaDa», «linguaA»). Удалите их. Думаю, это поможет.
It works backwards, too. Whilst it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model.
Смущает то, что значение по умолчанию related_name (т.е. _set ) не совпадает со значением по умолчанию related_query_name (т.е. ), но если вы установите пользовательский related_name (или default_related_name через Meta параметры модели), оно также будет использоваться по умолчанию related_query_name (как указано в документах).
Поле, связанное с фильтром Django, с помощью настраиваемого менеджера связанной модели
Как я могу применить аннотации и фильтры из настраиваемого набора запросов менеджера при фильтрации через связанное поле? Вот код, чтобы продемонстрировать, что я имею в виду.
Менеджер и модели
Попытка отфильтровать связанное поле с помощью менеджера
Если вы попробуете приведенный выше код, вы получите следующую ошибку:
TypeError: Related Field got invalid lookup: some_flag
Первым получает pk связанных OtherModel объектов.
Я не думаю, что то, что вы хотите, возможно.
1) Я думаю, вы не понимаете, что делают аннотации.
Generating aggregates for each item in a QuerySet
The second way to generate summary values is to generate an independent summary for each object in a QuerySet. For example, if you are retrieving a list of books, you may want to know how many authors contributed to each book. Each Book has a many-to-many relationship with the Author; we want to summarize this relationship for each book in the QuerySet.
Per-object summaries can be generated using the annotate() clause. When an annotate() clause is specified, each object in the QuerySet will be annotated with the specified values.
The syntax for these annotations is identical to that used for the aggregate() clause. Each argument to annotate() describes an aggregate that is to be calculated.
Итак, когда вы говорите:
что было бы очень медленно, и я не удивлен, что они этого не делают.
Возможное решение
не аннотируйте свое поле, а добавьте его как обычное поле в свою модель.
ajax and search #53
Comments
joeyac commented Aug 9, 2016
The text was updated successfully, but these errors were encountered:
azmeuk commented Aug 24, 2016
Can you give more details? What is your error exactly?
cristiancs commented Dec 9, 2016
Hi, looks like the problem is when you have a foreign key table:
10:59:39 AM web.1 | Internal Server Error: /table/ajax/bf36a02d72149d056fb3c275ccfe2846/ 10:59:39 AM web.1 | Traceback (most recent call last): 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/core/handlers/base.py», line 149, in get_response 10:59:39 AM web.1 | response = self.process_exception_by_middleware(e, request) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/core/handlers/base.py», line 147, in get_response 10:59:39 AM web.1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/views/generic/base.py», line 68, in view 10:59:39 AM web.1 | return self.dispatch(request, *args, **kwargs) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/views/generic/base.py», line 88, in dispatch 10:59:39 AM web.1 | return handler(request, *args, **kwargs) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/table/views.py», line 53, in get 10:59:39 AM web.1 | return BaseListView.get(self, request, *args, **kwargs) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/views/generic/list.py», line 174, in get 10:59:39 AM web.1 | context = self.get_context_data() 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/table/views.py», line 130, in get_context_data 10:59:39 AM web.1 | queryset = self.filter_queryset(queryset) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/table/views.py», line 77, in filter_queryset 10:59:39 AM web.1 | queryset = queryset.filter(get_filter_arguments(target)) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/db/models/query.py», line 790, in filter 10:59:39 AM web.1 | return self._filter_or_exclude(False, *args, **kwargs) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/db/models/query.py», line 808, in _filter_or_exclude 10:59:39 AM web.1 | clone.query.add_q(Q(*args, **kwargs)) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/db/models/sql/query.py», line 1243, in add_q 10:59:39 AM web.1 | clause, _ = self._add_q(q_object, self.used_aliases) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/db/models/sql/query.py», line 1263, in _add_q 10:59:39 AM web.1 | current_negated, allow_joins, split_subq) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/db/models/sql/query.py», line 1269, in _add_q 10:59:39 AM web.1 | allow_joins=allow_joins, split_subq=split_subq, 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/db/models/sql/query.py», line 1194, in build_filter 10:59:39 AM web.1 | lookup_class = field.get_lookup(lookups[0]) 10:59:39 AM web.1 | File «/Users/mhcristian/proyectos/cloaker/venv/lib/python2.7/site-packages/django/db/models/fields/related.py», line 693, in get_lookup 10:59:39 AM web.1 | raise TypeError(‘Related Field got invalid lookup: %s’ % lookup_name) 10:59:39 AM web.1 | TypeError: Related Field got invalid lookup: icontains
video0000 commented Mar 29, 2017
which error? ajax error? That `s because some columes are made of fields of function, you have to make that columes searchable=false
luisitoguanes commented Oct 2, 2017 •
Hello! I found this same error! how was it solved?
It only happened when using ajax with a model that has a fk.
Testing django admin search_fieldsВ¶
In the django admin you can add search fields. Very handy! You get a search field at the top of your admin page to quickly filter the results.
Here’s an example:
On the admin page that lists the books you want to have a search box. Not only for book titles, but you also want to search on authors’ names and get their books. Easy:
Let’s try it out in the admin. Oops:
You have to point at a proper texually-searchable field instead of directly to a model (via a ForeignKey field). It is easy to fix:
I’ve written a very simple test that tests all my ModelAdmin’s search_fields:
Works like a charm! It immediately reported an error in one of my search_fields 🙂
Note: I rely on print() to tell me what went wrong. Which works, as I use nose as a test runner, which suppresses the output unless the test fails.
About me
My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I’m happily married to Annie van Rees-Kooiman.
Weblog feeds
Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):
django admin related поле got invalid lookup: icontains
У меня получились вот такие Models:
У меня есть вот такие Admin Objects:
У самого list_display работает нормально но поиск всегда выдает ошибку говорящую:
2 ответа
Я пытаюсь добавить автора в поле search_field но он кидает ошибку- Related Field got invalid lookup: icontains models.py class Post(models.Model): STATUS_CHOICES = ( (‘draft’, ‘Draft’), (‘published’, ‘Published’), ) title = models.CharField(max_length=250) slug =.
Оказывается ошибка именно из-за
«the_image» является объектом FilerImageField, это и вызывает ошибку.
Это работает когда i превратили его в:
Behind the scene
Это из документации Django:
Когда кто-то делает поиск в админке поиска, Django разбивает поисковый запрос на слова и возвращает все объекты, которые содержат каждое из слов, case нечувствительный, где каждое слово должно быть хотя бы в одном из search_fields.
Надеюсь, это поможет!
Похожие вопросы:
Я пытаюсь выполнить запрос к моей базе данных с name, который содержит в себе в поле MainName который будет фильтровать Profile при данном запросе.
Я пытаюсь сделать поле vanKit searchable в своей админ странице. vanKit это ForeignKey и всякий раз когда я его добавляю мой список search_fields мне выдает эту ошибку Related Field got invalid.
Нужно с помощью django_elasticsearch_dsl искать по заданному тексту. Это должно работать как для полного слова так и для только для части мира. Как для пример и xample. С помощью python 3.6.
Я пытаюсь добавить автора в поле search_field но он кидает ошибку- Related Field got invalid lookup: icontains models.py class Post(models.Model): STATUS_CHOICES = ( (‘draft’, ‘Draft’).
У меня есть некоторые проблемы с django-autocomplete-light который я не могу разрешить самостоятельно. models.py from django.contrib.auth.models import User class UserProfile(models.Model): user =.
Я бы хотел иметь возможность искать пользователя и иметь его направляющую меня на список всех пользователей. Когда я пробую функцию поиска, то получаю вот такую ошибку: Related Field got invalid.
Мой model.py: from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save from django.urls import reverse from django.utils.text import.
Я пытаюсь сделать поиск для запроса в Django, заместо icontains lookup работает для поля title (CharField) но не для поля content (TextField). Я хочу сделать поиск если запрос существует в заголовке.
Устранение неполадок «Связанное поле имеет недопустимый поиск: icontains»
У меня есть следующие модели в models.py:
В то время как в admin.py у меня есть следующее:
Но когда я пытаюсь выполнить поиск на странице администратора в таблице ListinoTraduttore, у меня появляется следующая ошибка:
9 ответов
Вы пытались добавить __fieldname на тех Lingua ссылки в ListinoTraduttoreAdmin поля поиска, например:
Это должно (надеюсь) упростить ответ.
Не фильтруйте само поле ForeignKey!
чтобы (обратите внимание на два подчеркивания)
name представляет имя поля из таблицы, с которой у нас есть отношение ForeinKey.
Надеюсь это поможет
Убедитесь, что вы не добавляете Foreignkey или ManyToManyField в поле search_field напрямую.
Вместо этого используйте двойное подчеркивание Django. документы
Требуется двойное подчеркивание
Это сработало для меня.
Найдите поле внешнего ключа, используя my_related_object__first_attribute:
Он работает и в обратном направлении. Хотя это можно настроить, по умолчанию вы ссылаетесь на «обратную» связь при поиске, используя имя модели в нижнем регистре.
Smart Host Filter field «inventory» isn’t working as expected #7201
Comments
rh-dluong commented Jun 1, 2020
ISSUE TYPE
SUMMARY
When searching for inventory:example in Tower, it returns the following:
The below is the network debug:
ENVIRONMENT
STEPS TO REPRODUCE
Try to search for a key in smart host filter using inventory:
EXPECTED RESULTS
Returns the query successfully
ACTUAL RESULTS
ADDITIONAL INFORMATION
It looks like inventory is both in Related Fields and Fields for this window. Also, searching for the inventory’s id or name gives that same icontains error.
The text was updated successfully, but these errors were encountered:
Ben2064 commented Jun 23, 2020 •
I’m running into the same issue on:
AWX 11.2
Chrome
Kubernetes (server)
Win 10 (client)
So it’s probably not version/browser/os related. For us this is making smart inventories essentially useless as we absolutely need to be able to filter by inventory/groups to make use of them in most cases.
Toucan-Sam commented Aug 19, 2020 •
TLDR: inventory.name.icontains:»name of your inventory»
I’m also experiencing this and just making some observations.
AWX: 13.0.0 w/ Ansible 2.9.10
It looks like the ‘inventory’ field is both a ‘field’ and a ‘related field’.
ERROR: Related Field got invalid lookup: icontains
Might be related to icontains working on ‘fields’ but not ‘related fields’? Appears to be the only duplicate named item. Either way the error message wasn’t particularly clear about why I couldn’t search for the thing.
Ошибка при поиске в админке Django
Вот соответствующая часть моего кода:
Я получил ошибку TypeError вместо:
Какое значение я должен выставить search_fields чтобы?
2 ответа
У меня есть CMS работающая на Django 1.4 и база данных это Postgresql 9.1. У меня в CMS много контента и вопрос, с которым я столкнулся щас в том, что поиск Django Admin занимает вечно время для извлечения результатов. Я хотел бы узнать есть ли варианты оптимизировать это поведение поиска Django.
Есть ли все-таки для добавления функционала Datatables в интерфейс админки django. Я использую Django + Mezzanine и для моего проекта нам нужна возможность сортировки по каждому столбцу, иметь пагинацию, поиск и т.д.
Проверьте search_fields документацию, так как там сказано
Эти поля должны быть каким-то текстовым полем, например CharField или TextField. Также вы можете выполнить связанный lookup по ForeignKey или ManyToManyField с нотацией lookup API «follow»:
Так что в вашем случае
Также заметьте не говорит о том, что вы могли использовать вычисляемое свойство так, как вы пытались вначале
Напишите свой класс админки вот так
Поля поиска должны быть вот так identity__fieldname
Похожие вопросы:
Моя модель выглядит так: class Asset(models.Model): serial_number = models.CharField(max_length=100, unique=True) asset_tag = models.CharField(max_length=100, unique=True) class.
Я пытаюсь настроить django admin page для своего сайта. Для моего локального dev сервера он сейчас работает нормально, но однажды я прокинул код на server, и попытался открыть страницу admin, он мне.
Я пытаюсь настроить привязки админки Django для конкретной модели, чтобы я мог быстро фильтровать по точному значению конкретного поля. Я знаю, что могу вручную манипулировать с GET параметрами.
У меня есть CMS работающая на Django 1.4 и база данных это Postgresql 9.1. У меня в CMS много контента и вопрос, с которым я столкнулся щас в том, что поиск Django Admin занимает вечно время для.
Есть ли все-таки для добавления функционала Datatables в интерфейс админки django. Я использую Django + Mezzanine и для моего проекта нам нужна возможность сортировки по каждому столбцу, иметь.
Возможно ли сделать на интерфейсе Django Admin обратный реляционный поиск? Моя схема БД Django app состоит из следующих моделей: class Tag(models.Model): title = models.CharField(max_length=50).
Q Lookups TypeError Django
Я пока реализовал поисковую строку но когда я произвожу поиск оно жалуется:
В чем тут вопрос именно?
Models.py
1 ответ
Поле поиска в шаблоне Django Как создать поле поиска в шаблоне Django похожее на это изображение http://asciicasts.com/system/photos/1204/original/E354I01.png Пробую такое в github https://github.com/rg3915/vendas/commit/e0c67fd8154a3b8e450ec3db38705cdd7efc1350 Но не знаю как доделать.
Похожие вопросы:
Я разрабатываю сайт щас, который, раз вы авторизуетесь, на верхней части страницы всегда будет присутствовать поисковая строка. Мне интересно, каким лучшим способом спроектировать эту парадигму в.
Есть ли простой способ добавить возможность поиска по полям в Django? Также дайте мне, пожалуйста, знать, что такое Lucene поиск.
Пытаюсь понизить требования к (рабочему) сайту Django/wagtail с Django 1.9.6 до Django 1.8.13 получаю TypeError при попытке доступа к любому из моих url-адресов wagtail (не важно, админ это или мой.
У меня есть django приложение и это приложение запущенное в моем локальном сервере. Но оно не может запустить мой digitalocean сервер. При входе в это приложение, выдавать эту ошибку Internal Server.
Поле поиска в шаблоне Django Как создать поле поиска в шаблоне Django похожее на это изображение http://asciicasts.com/system/photos/1204/original/E354I01.png Пробую такое в github.
Пытаюсь использовать Django для настройки email и простую форму, но не получается. Как можно исправить ошибку? python==3.5.1 Django==1.8.8 Кидается следующая ошибка: TypeError at /contact not all.
Я портирую django-приложение с 1.х на 2.1 и застрял с ошибкой, которая гласит TypeError: object() takes no parameters. Я пытаюсь решить проблему уже довольно долгое время но даже не получил.
Я совсем новичок в Django-phython. Я пытаюсь заполонить результаты поиска внутри html тега input формы. С учетом того, что поиск возвращает. У меня есть view, которое рендерит html код, передавая.
Я новичок в werkzeug и у меня получается TypeError: init () takes least 2 arguments (1 given), когда я пытаюсь посетить тестовую страницу после установки и настройки. Werkzeug же предоставляет.
Вот я искал в этом посте, чтобы попробовать и решить некоторые вопросы, встречающиеся в моем туториале по Django: TypeError: ‘choice_text’ is an invalid keyword argument for this function в.
Русские Блоги
Ошибка фонового поиска Django: в связанном поле неверный поиск: icontains
Эта ошибка обычно возникает из-за того, что вы использовали внешний ключ в search_fields в файле admin.py без указания конкретного поля.
search_fields = (‘title’, ‘author__name’, )
Полное содержание ошибки:
Интеллектуальная рекомендация
Самый простой, но самый простой оператор самоприращения ++ на языке C (например)
Оператор SQLite (1): табличные операции и ограничения
Один, операции, связанные с таблицами Создать таблицу Пример: Удалить таблицу Пример: При удалении таблицы, чтобы избежать ошибок, вы также можете добавить оператор IF EXISTS, например: Изменить табли.
Просмотреть справочную документацию Python
просмотр функции dirСвойства объекта __doc__ ПросмотрСправочная документация по атрибуту объекта просмотр функции справкиСправочная документация по атрибуту объекта.
Кривая зрелости новых технологий Gartner 2018 (пять технологических трендов)
Источник изображения: Unsplash источник Технологический альянс архитекторов Если вам нужно перепечатать, пожалуйста, свяжитесь с первоначальным автором для авторизации Недавно Gartner опубликовал нову.
Вам также может понравиться
Почему в правиле YSLOW Yahoo рекомендует использовать GET вместо POST?
Перейдите по ссылке: http://blog.csdn.net/21aspnet/article/details/6668868. задний план: В прошлую пятницу на тренинге для интерфейсных инженеров компании были упомянуты некоторые советы по оптимизаци.
Linux 2 unit4 раздел диска
unit4 Простой раздел и файловая система в системе управления ### Раздел диска ### делится на основной раздел и расширенный раздел (может быть разделен на логический раздел
Тензор потока исследования прикроватных записок (1)
Переменные tenorflowAPI заметки переменная Переменная вспомогательная функция Сохранить и восстановить переменные Общая переменная Редкое обновление переменной объяснять переменная Переменная получает.
Пример WebSocket в Springboot
WebSocket Что такое WebSocket WebSocket предоставляет функцию дуплексной асинхронной связи между браузером и сервером, то есть браузер может отправлять сообщения на сервер, а сервер также может отправ.
программирование потока потока
Ggtcf
Subscribe to this blog
Does detail obscure or enhance action?
Why can’t I see bouncing of a switch on an oscilloscope?
What defenses are there against being summoned by the Gate spell?
Important Resources for Dark Age Civilizations?
Did Shadowfax go to Valinor?
Is it possible to run Internet Explorer on OS X El Capitan?
Watching something be written to a file live with tail
How can I make my BBEG immortal short of making them a Lich or Vampire?
How old can references or sources in a thesis be?
RSA: Danger of using p to create q
What are these boxed doors outside store fronts in New York?
A case of the sniffles
Do I have a twin with permutated remainders?
What does it mean to describe someone as a butt steak?
How to format long polynomial?
How does quantile regression compare to logistic regression with the variable split at the quantile?
Today is the Center
Is it legal for company to use my work email to pretend I still work there?
Arrow those variables!
Client team has low performances and low technical skills: we always fix their work and now they stop collaborate with us. How to solve?
LWC SFDX source push error TypeError: LWC1009: decl.moveTo is not a function
Modeling an IP Address
Can a Cauchy sequence converge for one metric while not converging for another?
Is it possible to do 50 km distance without any previous training?
Can’t add field to ModelForm at __init__Show information of subclass in list_display djangoDjango FieldError at /admin/app/modelClass/How to expose some specific fields of model_b based on a field of model_a?django admin related Field got invalid lookup: icontainsDjango: `Related Field got invalid lookup: icontains`How to define Mode with generic ForeignKey in DjangoHow to remove Django redundant inner joinHow to display multiple objects from fields in Django AdminSchool attendence model
I am trying to make the «vanKit» field searchable in my admin page. «vanKit» is a ForeignKey and whenever I add it it my search_fields list it gives me this error «Related Field got invalid lookup: icontains». Here’s my code:
I tried to use search_fields = [‘vanKit__name’] like the other stack overflow answers suggested but that did not work for me. Can anyone explain why I am getting this error and how to get around it? I am using Django 2.1 and python 3.7. Thanks in advance!
What does the vanKit model look like? Are you sure VanKit.name is a string field?
– farooq
Mar 9 at 1:14
– Waket Zheng
Mar 9 at 3:39
vanKit is a foreign key to van_kit. The name of the van kits are specified by » van_kit_name = models.CharField(max_length=100)» in the van_kit class
– Tank12
Mar 9 at 7:40
I’ll make those changes to correct the class names as well
– Tank12
Mar 9 at 7:41
I am trying to make the «vanKit» field searchable in my admin page. «vanKit» is a ForeignKey and whenever I add it it my search_fields list it gives me this error «Related Field got invalid lookup: icontains». Here’s my code:
I tried to use search_fields = [‘vanKit__name’] like the other stack overflow answers suggested but that did not work for me. Can anyone explain why I am getting this error and how to get around it? I am using Django 2.1 and python 3.7. Thanks in advance!
What does the vanKit model look like? Are you sure VanKit.name is a string field?
– farooq
Mar 9 at 1:14
– Waket Zheng
Mar 9 at 3:39
vanKit is a foreign key to van_kit. The name of the van kits are specified by » van_kit_name = models.CharField(max_length=100)» in the van_kit class
– Tank12
Mar 9 at 7:40
I’ll make those changes to correct the class names as well
– Tank12
Mar 9 at 7:41
I am trying to make the «vanKit» field searchable in my admin page. «vanKit» is a ForeignKey and whenever I add it it my search_fields list it gives me this error «Related Field got invalid lookup: icontains». Here’s my code:
I tried to use search_fields = [‘vanKit__name’] like the other stack overflow answers suggested but that did not work for me. Can anyone explain why I am getting this error and how to get around it? I am using Django 2.1 and python 3.7. Thanks in advance!
I am trying to make the «vanKit» field searchable in my admin page. «vanKit» is a ForeignKey and whenever I add it it my search_fields list it gives me this error «Related Field got invalid lookup: icontains». Here’s my code:
I tried to use search_fields = [‘vanKit__name’] like the other stack overflow answers suggested but that did not work for me. Can anyone explain why I am getting this error and how to get around it? I am using Django 2.1 and python 3.7. Thanks in advance!
What does the vanKit model look like? Are you sure VanKit.name is a string field?
– farooq
Mar 9 at 1:14
– Waket Zheng
Mar 9 at 3:39
vanKit is a foreign key to van_kit. The name of the van kits are specified by » van_kit_name = models.CharField(max_length=100)» in the van_kit class
– Tank12
Mar 9 at 7:40
I’ll make those changes to correct the class names as well
– Tank12
Mar 9 at 7:41
What does the vanKit model look like? Are you sure VanKit.name is a string field?
– farooq
Mar 9 at 1:14
– Waket Zheng
Mar 9 at 3:39
vanKit is a foreign key to van_kit. The name of the van kits are specified by » van_kit_name = models.CharField(max_length=100)» in the van_kit class
– Tank12
Mar 9 at 7:40
I’ll make those changes to correct the class names as well
– Tank12
Mar 9 at 7:41
What does the vanKit model look like? Are you sure VanKit.name is a string field?
– farooq
Mar 9 at 1:14
What does the vanKit model look like? Are you sure VanKit.name is a string field?
– farooq
Mar 9 at 1:14
– Waket Zheng
Mar 9 at 3:39
– Waket Zheng
Mar 9 at 3:39
vanKit is a foreign key to van_kit. The name of the van kits are specified by » van_kit_name = models.CharField(max_length=100)» in the van_kit class
– Tank12
Mar 9 at 7:40
vanKit is a foreign key to van_kit. The name of the van kits are specified by » van_kit_name = models.CharField(max_length=100)» in the van_kit class
– Tank12
Mar 9 at 7:40
I’ll make those changes to correct the class names as well
– Tank12
Mar 9 at 7:41
I’ll make those changes to correct the class names as well
– Tank12
Mar 9 at 7:41
1 Answer
1
So I figured it out, I had to use «search_fields = [‘vanKit__van_kit_name’]» van_kit_name is the field that held the name of the van kits in the van_kit model that «vanKit» relates to through a Foreign Key. I had to access the Char Field that held the van kit’s name in the actual van_kit model.
Issues
Context Navigation
#23351 closed Cleanup/optimization (duplicate)
Admin Search Field error for related lookup
Reported by: | Ezequiel Bertti | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.7 |
Severity: | Normal | Keywords: | |
Cc: | florent.pastor@…, zeraien | Triage Stage: | Unreviewed |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
I’m using Django Version 1.7c2 and I have these two models :
And this Admin Class:
And i’m getting this error
FieldError at /admin/app/subject/
Relation fields do not support nested lookups
on django\db\models\fields\related.py in get_lookup_constraint
raise exceptions.FieldError(‘Relation fields do not support nested lookups’)
Change History (4)
comment:1 follow-up: 3 Changed 8 years ago by Ramiro Morales
I can’t reproduce this with the information provided and using a simple setup containing only the code shown by the OP.
Reopne if you can post more details.
comment:2 Changed 8 years ago by Florent Pastor
The admin class is still the same :
When I try to search, I get this issue :
By the way, I run Django 1.6.5, I did not test my project under django 1.7.
comment:3 in reply to: 1 Changed 8 years ago by zeraien
Cc: | zeraien added |
---|---|
Resolution: | worksforme |
Severity: | Release blocker → Normal |
Status: | closed → new |
Type: | Uncategorized → Bug |
Version: | 1.7-rc-2 → 1.7 |
I can’t reproduce this with the information provided and using a simple setup containing only the code shown by the OP.
Reopne if you can post more details.
I discovered the problem seems to be related to this ticket: https://code.djangoproject.com/ticket/23697
If using this: search_fields = (‘module__name’,) but name does not exist in the module model, this error is thrown.
Using django 1.7.3
comment:4 Changed 8 years ago by Simon Charette
Resolution: | → duplicate |
---|---|
Status: | new → closed |
Type: | Bug → Cleanup/optimization |
Thanks for the report but let’s keep this ticket closed by marking it as a duplicate instead and move all discussion to #23697.
The fix suggested by Tim on #23697 should prevent reports similar to this one which were probably caused by a simple typo in the field name.
icontains и getlist django python
Мы пытаемся вернуть список названий для API Django, в котором заголовок может иметь несколько ключевых слов.
Так например, если мы используем метод __icontains для поиска «деньги» и «мир» ( api.com/?keyworld=money&keyword=world ) это вернет все записи, которые содержат деньги, мир или и то, и другое.
Связанный оператор SQL такой:
Мы пытаемся использовать этот код, чтобы позволить пользователю иметь несколько ключевых слов для оператора __icontains а также несколько источников, поэтому конечная цель такая:
Our code:
2 ответа
Я пока что использую простые DAL, и django-filter отдельно но у меня беда с использованием DAL с django-filter. Я пока что прочитал эту страницу: django-filter со светом django autocomplete Но я все еще запутался. У меня есть filter class вроде этого ниже, и я хочу использовать DAL по полю.
Вы не можете выполнить функцию __icontains со списком, но вы можете например сконструировать функцию, которая для списка сконструирует логическое ИЛИ этих значений. Например:
Вы можете потом вызвать функцию unroll_lists_or с queryset, и каждый элемент должен быть итерируемым (например списком). Она потом выполнит or-логику между элементами списка, и and-логику между разными ключами. В случае, если итерируемый элемент пуст, он игнорируется.
Поэтому мы можем потом написать проверку как:
В случае, если title содержит два элемента (так title == [title1, title2] ), а source содержит три элемента (так source = [source1, source2, source3] ), то это приведет к:
Edit: При переходе по ссылке api и передаче в параметрах, фильтрация будет происходить исходя из того, что передано в:
SQL Эквивалент:
Я создал приложение с помощью ‘django nonrel’ и нахожусь с помощью ‘django dbindexer’ для допуска нормальных lookups Django. Файл настроек таков как ниже myproject/settings.py from djangoappengine.settings_base import * import os DATABASES[‘native’] = DATABASES[‘default’] DATABASES[‘default’] =.
Похожие вопросы:
Я пытаюсь сделать поле vanKit searchable в своей админ странице. vanKit это ForeignKey и всякий раз когда я его добавляю мой список search_fields мне выдает эту ошибку Related Field got invalid.
Нужно с помощью django_elasticsearch_dsl искать по заданному тексту. Это должно работать как для полного слова так и для только для части мира. Как для пример и xample. С помощью python 3.6.
У меня была Django форма, которая подала список значений в мою вьюху. Я сначала попробовал извлечь список с помощью метода get но обнаружил, что он только вернул последнее из них и мне следует.
Я пока что использую простые DAL, и django-filter отдельно но у меня беда с использованием DAL с django-filter. Я пока что прочитал эту страницу: django-filter со светом django autocomplete Но я все.
У меня на данный момент есть Django приложение и база данных postgres. Я хочу иметь поисковую строку, которая позволяет пользователям вводить в значение и она будет искать по какому-то из полей.
Я создал приложение с помощью ‘django nonrel’ и нахожусь с помощью ‘django dbindexer’ для допуска нормальных lookups Django. Файл настроек таков как ниже myproject/settings.py from.
Я пытаюсь сделать поиск по списку значений в нескольких столбцах в postgres (через django). Я смог использовать SearchQuery и SearchVector и это прекрасно работает если одному из значений поиска.
Searching for a venue gives error about google maps API
Bug Description
When you search for a venue (using this page http:// loco.ubuntu. com/venues/) after pressing the search icon, the next page is white and there is a javascript alert popup that says «This web site needs a different Google Maps API key. A new key can be generated at http:// code.google. com/apis/ maps/.»
Related branches
Traceback (most recent call last):
File «/var/lib/ python- support/ python2. 5/django/ db/models/ sql/query. py», line 1254, in add_q
self. add_q(child, used_aliases)
File «/var/lib/ python- support/ python2. 5/django/ db/models/ sql/query. py», line 1258, in add_q
can_ reuse=used_ aliases)
File «/var/lib/ python- support/ python2. 5/django/ db/models/ sql/query. py», line 1201, in add_filter
self. where.add( (alias, col, field, lookup_type, value), connector)
File «/var/lib/ python- support/ python2. 5/django/ db/models/ sql/where. py», line 48, in add
params = field.get_ db_prep_ lookup( lookup_ type, value)
File «/var/lib/ python- support/ python2. 5/django/ db/models/ fields/ related. py», line 156, in get_db_prep_lookup
raise TypeError, «Related Field has invalid lookup: %s» % lookup_type
TypeError: Related Field has invalid lookup: icontains
Django поле поиска не работает
Я бы хотел иметь возможность искать пользователя и иметь его направляющую меня на список всех пользователей.
Она трассировывает обратно на эту строку:
Любые идеи? Заранее спасибо!
views.py:
models.py:
1 ответ
Поле поиска в шаблоне Django Как создать поле поиска в шаблоне Django похожее на это изображение http://asciicasts.com/system/photos/1204/original/E354I01.png Пробую такое в github https://github.com/rg3915/vendas/commit/e0c67fd8154a3b8e450ec3db38705cdd7efc1350 Но не знаю как доделать.
Похожие вопросы:
Я пытаюсь реализовать pulldown поле, которое содержит список названий стран в форме Customer Billing Information, используя поле ModelChoiceField. Однако, когда я пытаюсь отрендерить форму, я.
У меня реализована функция поиска с помощью Django SearchFilter DRF которая отлично работает но вопрос в том что я не хочу отображать весь запрос когда я передаю в поле поиска ничего не работает.
Я знаю это ооочень базовый вопрос. В Django я успешно создал админ панель. Теперь я хочу добавить кастомное поле поиска в одном своем поле а именно Photo поле. Но я незнаю как добавить кастомное.
Поле поиска в шаблоне Django Как создать поле поиска в шаблоне Django похожее на это изображение http://asciicasts.com/system/photos/1204/original/E354I01.png Пробую такое в github.
Вот, у меня есть many to many field define в Django модели и я хочу сделать поиск, что бы many to many field в моем Django admin поле поиска. Как мы не можем поместить many to many field в поле.
Я разрабатываю проект с django, является магазином eCommerce. И я хочу реализовать searchbox для поиска продуктов по нему. Я пока разрабатывал с помощью ajax, но на данный момент что i поиск.
Я использую django-haystack для поиска на своем сайте. Моя проблема заключается в том, я бы хотел иметь результаты поиска сверху если в определенном поле был найден термин поиска. Скажем я делаю.
В своем django приложении я вывожу список элементов (имя друзей) благодаря циклу:
Я пытаюсь сделать поле «vanKit» searchable в своей админ странице. «vanKit» это ForeignKey и всякий раз когда я его добавляю мой список search_fields мне выдает эту ошибку «Related Field got invalid lookup: icontains». Вот мой код:
Я пытался использовать search_fields = [‘vanKit__name’] как и другие ответы stack overflow подсказал но что у меня не сработало. Кто нибудь может объяснить почему я получаю эту ошибку и как её обойти? Я использую Django 2.1 и python 3.7. Заранее спасибо!
1 ответ
Я пытаюсь добавить автора в поле search_field но он кидает ошибку- Related Field got invalid lookup: icontains models.py class Post(models.Model): STATUS_CHOICES = ( (‘draft’, ‘Draft’), (‘published’, ‘Published’), ) title = models.CharField(max_length=250) slug =.
Похожие вопросы:
Я пытаюсь отфильтровать фильд many-to-many по модели, где мне дают запятую разделенный список id в URL. ids = 3,7 cat_ids = self.request.QUERY_PARAMS.get(‘cat_ids’, None) super(Filter.
Я пытаюсь выполнить запрос к моей базе данных с name, который содержит в себе в поле MainName который будет фильтровать Profile при данном запросе.
Нужно с помощью django_elasticsearch_dsl искать по заданному тексту. Это должно работать как для полного слова так и для только для части мира. Как для пример и xample. С помощью python 3.6.
Я пытаюсь добавить автора в поле search_field но он кидает ошибку- Related Field got invalid lookup: icontains models.py class Post(models.Model): STATUS_CHOICES = ( (‘draft’, ‘Draft’).
У меня есть некоторые проблемы с django-autocomplete-light который я не могу разрешить самостоятельно. models.py from django.contrib.auth.models import User class UserProfile(models.Model): user =.
Я бы хотел иметь возможность искать пользователя и иметь его направляющую меня на список всех пользователей. Когда я пробую функцию поиска, то получаю вот такую ошибку: Related Field got invalid.
Мой model.py: from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save from django.urls import reverse from django.utils.text import.
У меня получились вот такие Models: @python_2_unicode_compatible class Media(models.Model): the_image = FilerImageField(null=True) title = models.CharField(verbose_name=Title, max_length=255.
Я пытаюсь сделать поиск для запроса в Django, заместо icontains lookup работает для поля title (CharField) но не для поля content (TextField). Я хочу сделать поиск если запрос существует в заголовке.
Search failing for SlugField #23
Comments
vincentwhales commented Aug 23, 2018
i have the following:
It seems like typing anything in the search field will result in the following:
The text was updated successfully, but these errors were encountered:
izimobil commented Nov 16, 2018
You need to provide more infos, especially your HTML/JS code
Rubyj commented Dec 19, 2018 •
@vincentwhales @izimobil I have found the solution to make my example (which I imagine is the same as the original question, work)
in the serializer you must have something like offer = serializers.ReadOnlyField(source=’x.y’)
Then, in the JS columns specifications you must have your column defined as such
Where x is the name of your foreign relationship variable as defined in the model and y is the variable name of the field in that model. This worked for me when I encountered the same issue.
Python-сообщество
Уведомления
#1 Ноя. 30, 2021 18:55:30
# здесь штрих код и название
class Art(models.Model):
bar = models.CharField(max_length=13, verbose_name = “Штрихкод”, db_column = “Штрихкод”, default=“”,,primary_key=True)
nom = models.CharField(max_length=200, verbose_name = “Номенклатура”, db_column = “Номенклатура”, default=“”)
# здесь цена
class Price(models.Model):
art = models.ForeignKey(Art, on_delete=models.SET_NULL, null=True)
pr = models.DecimalField(decimal_places=2, max_digits=10, verbose_name = “Цена”, db_column = “Цена”, default=0)
# заливаю таблицы скриптом из эксель файла
# делаю запрос получить все записи из таблицы Price и прилепить название номенклатуры (если не найдено то там null)
data = Price.objects.values(‘art_id’, ‘art__nom’, ‘pr’)
можно конечно завести отдельно ForeignKey а отдельно штрих код, но не хочеться заводить ещё одно поле
слишком большой объем номенклатуры
Отредактировано consta (Ноя. 30, 2021 21:08:24)
Источники:
- http://stackoverflow.com/questions/72845609/multiple-search-with-django-foreign-key-related-field-got-invalid-lookup-icont
- http://stackoverflow.com/questions/46884258/django-admin-related-field-got-invalid-lookup-icontains
- http://stackoverflow.com/questions/68091477/django-admin-panel-search-bar-not-work-related-field-got-invalid-lookup-iconta
- http://qastack.ru/programming/11754877/troubleshooting-related-field-has-invalid-lookup-icontains
- http://stackoverflow.com/questions/67451160/related-field-got-invalid-lookup
- http://stackoverflow.com/questions/50777152/drf-queryset-filter-using-contains-field-lookup-on-slugrelatedfield
- http://stackoverflow.com/questions/29262606/typeerror-related-field-got-invalid-lookup-balance/29262763
- http://stackoverflow.com/questions/29262606/typeerror-related-field-got-invalid-lookup-balance
- http://stackoverflow.com/questions/43061090/error-searching-in-django-admin
- http://stackovergo.com/ru/q/3246204/troubleshooting-related-field-has-invalid-lookup-icontains
- http://code.djangoproject.com/ticket/23351
- http://stackoverflow.com/questions/44558180/django-filter-related-field-using-related-models-custom-manager
- http://stackoverflow.com/questions/39481905/django-foreign-key-lookup-aggregate-data
- http://stackoverflow.com/questions/21698120/how-to-search-by-related-model-field-using-django-extra-views
- http://stackoverflow.com/questions/21698120/how-to-search-by-related-model-field-using-django-extra-views/21708704
- http://code.djangoproject.com/ticket/2331?cversion=0&cnum_hist=7
- http://stackoverflow.com/questions/21698120/how-to-search-by-related-model-field-using-django-extra-views?lq=1
- http://github.com/noirbizarre/django-eztables/issues/8
- http://stackoverflow.com/questions/1227091/how-to-dynamically-provide-lookup-field-name-in-django-query/1239602
- http://github.com/izimobil/django-rest-framework-datatables/issues/6
- http://django.fun/qa/420756/
- http://stackoverflow.com/questions/1227091/how-to-dynamically-provide-lookup-field-name-in-django-query?lq=1
- http://stackoverflow.com/questions/5139778/in-django-using-fiter-then-get-on-queryset
- http://www.yodiaditya.com/solve-django-admin-search-error-related-fields-has-invalid-lookup-icontains/
- http://www.stackfinder.ru/questions/11754877/troubleshooting-related-field-has-invalid-lookup-icontains
- http://www.stackfinder.ru/questions/44558180/django-filter-related-field-using-related-models-custom-manager
- http://github.com/shymonk/django-datatable/issues/53
- http://reinout.vanrees.org/weblog/2015/10/29/testing-admin-search-fields.html
- http://coderoad.ru/46884258/django-admin-%D1%81%D0%B2%D1%8F%D0%B7%D0%B0%D0%BD%D0%BD%D0%BE%D0%B5-%D0%BF%D0%BE%D0%BB%D0%B5-%D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D0%BB%D0%BE-%D0%BD%D0%B5%D0%B2%D0%B5%D1%80%D0%BD%D1%8B%D0%B9-%D0%BF%D0%BE%D0%B8%D1%81%D0%BA-icontains
- http://stackru.com/questions/41282122/ustranenie-nepoladok-svyazannoe-pole-imeet-nedopustimyij-poisk-icontains
- http://github.com/ansible/awx/issues/7201
- http://coderoad.ru/43061090/%D0%9F%D0%BE%D0%B8%D1%81%D0%BA-%D0%BE%D1%88%D0%B8%D0%B1%D0%BE%D0%BA-%D0%B2-Django-admin
- http://coderoad.ru/43094818/%D0%92%D0%BE%D0%BF%D1%80%D0%BE%D1%81-%D0%9F%D0%BE%D0%B8%D1%81%D0%BA%D0%B0-TypeError-Django
- http://russianblogs.com/article/1236936531/
- http://ggtcf.blogspot.com/2019/04/related-field-got-invalid-lookup.html
- http://code.djangoproject.com/ticket/23351?cversion=0&cnum_hist=3
- http://coderoad.ru/51031397/icontains-%D0%B8-getlist-django-python
- http://bugs.launchpad.net/loco-team-portal/+bug/600198
- http://coderoad.ru/29155158/Django-%D0%BF%D0%BE%D0%BB%D0%B5-%D0%BF%D0%BE%D0%B8%D1%81%D0%BA%D0%B0-%D0%BD%D0%B5-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0%B5%D1%82
- http://coderoad.ru/55072980/%D0%A1%D0%B2%D1%8F%D0%B7%D0%B0%D0%BD%D0%BD%D0%BE%D0%B5-%D0%BF%D0%BE%D0%BB%D0%B5-%D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D0%BB%D0%BE-%D0%BD%D0%B5%D0%B2%D0%B5%D1%80%D0%BD%D1%8B%D0%B9-%D0%BF%D0%BE%D0%B8%D1%81%D0%BA-icontains-Django-2-1
- http://github.com/izimobil/django-rest-framework-datatables/issues/23
- http://python.su/forum/topic/40953/