我的 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' python user_profile = requests.get('https://api.github.com/users/{0}'.format(str(v ar1))) 内容=字典() 内容['用户'] = user_profile.json() 但是 var1 不能被替换字段替换,API 给我一个奇怪的错误
请您参考如下方法:
有一个使用 bool 运算符的有用搜索,您可以使用 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
干杯 亨利
