我的models.py文件中有一个名为Search的模型。我进行了迁移,除一个问题外,其他所有东西都工作正常。在我的views.py文件中,我创建了一个名为var1的变量,该变量将“ search_query”字段查询到数据库中,但是很遗憾,它无法分配该变量。
请帮助我如何访问我的模型以运行此行,
var1 = Search.objects.latest('search_query')
这是我的models.py文件,
from django.db import models
class Search(models.Model):
search_query = models.CharField(max_length=64)
views.py文件,
from django.shortcuts import render, redirect
import requests
from git_profile.forms import SearchForm
from git_profile.models import Search
def index(request):
var1 = Search.objects.latest('search_query')
编辑:
我想用此替换替换“ var1”
pythonuser_profile = requests.get('https://api.github.com/users/{0}'.format(str(var1)))content = dict()content['user'] = user_profile.json()
但是var1不能被替换字段替换,并且API给了我奇怪的错误
最佳答案
使用布尔运算符进行了有用的搜索,可以使用from django.db.models import Q # filter using operators '&' or '|'
。
例:
class RestaurantListView(ListView):
def get_queryset(self):
slug = self.kwargs.get("slug")
if slug:
queryset = RestaurantLocation.objects.filter(
Q(category__iexact=slug) |
Q(category__icontains=slug)
)
else:
queryset = RestaurantLocation.objects.all()
return queryset
有关使用查询集的更多信息,请参考https://docs.djangoproject.com/en/1.11/ref/models/querysets/
https://simpleisbetterthancomplex.com/tutorial/2016/11/28/how-to-filter-querysets-dynamically.html
干杯
亨利
关于python - 如何从views.py文件查询Django模型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46288478/