我在Django 1.11中有一个这样定义的模型:
class MyModel(Models.Model):
... some fields...
created_date = models.DateTimeField() #YYYY-MM-DD h:m:s
现在我希望能够在我的模板中按日期搜索im MyModel。为此,我扩展了change_list,一切都是正确的。
我的问题是:我必须为具有特定created_date的retrive对象做些什么?
假设您想要在2017-12-13创建的元素。 如果我去shell,我通过以下方式实现:
MyModel.objects.filter(created_date__date='2017-12-13')
一切正常,我得到了我的数据。 但为什么__date运算符不能在URL中工作?如果我将__date运算符放在url中,如下所示:
127.0.0.1:8000/admin/.../?created_date__date=2017-12-13
我收到错误:/?e = 1
所以我通过使用__lte和__gte运算符测试了另一种方法。 就像你想要在2017-12-13创建对象之前一样,所以我以这种方式组合了__lte和__gte运算符:
MyModel.objects.filter(created_date__gte='2017-12-13', created_date__lte='2017-12-13')
但在这种情况下,我得到一个空的查询集。 也是这样:
127.0.0.1:8000/admin/.../?created_date__gte=2017-12-13&created_date__lte=2017-12-13
所以,我的问题:
答案 0 :(得分:1)
If you want to search function in django admin, you should add search_fields
in your ModelAdmin.
I don't know well about your model admin (cause you didn't upload it). But if you only register model to admin, try using ModelAdmin
from django.contrib import admin
from Myapp.models import MyModel
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
# you can set so many things in admin. please check django doc
...
# be aware it should be tuple. If you have only one, please add comma
search_fields = ('created_at',)
Then you can see search input in your admin page. If you search by 2017-12-18
(or just 2017
or 2017-09
is also possible), you can get search get parameter in your url (such as admin/.../?q=2017-09-29
)
Now you can use that url in admin.
Happy hacking!