2017-09-18 3 views
-2

models.pyファイルにSearchという名前のモデルがあります。私は移行を行い、1つの問題を除いてすべてが完全に正常に動作しています。私のviews.pyファイルでは、 "search_query"フィールドをデータベースに照会するvar1という変数を作成しましたが、残念ながらその変数を割り当てることはできませんでした。 、このラインを動作するように私のモデルにアクセスする方法を私を助けここviews.pyファイルからDjangoモデルをクエリする方法は?

var1 = Search.objects.latest('search_query'),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'), search_query 

EDITでください。

この交換で「var1」を交換したい あなたが最も辞書を作成して、プロパティに選択変数を割り当てると、このようにビューに辞書を渡すあなたのビューで が、交換用のフィールドとAPIによりVAR1置き換えることができない私に奇妙なエラーが発生します

+1

を参照してくださいドットがあるはずコンマがあります。 –

+0

あなたはあなたのクエリで何をしたいのかについて少し洞察できますか? –

+0

私は 'var1'をこの置き換え '' 'pythonに置き換えたいと思っています。user_profile = requests.get( 'https://api.github.com/users/ {0}' .format(str(v ar1))) = dictの() コンテンツ[「ユーザー」] = user_profile.json(コンテンツ) '' ' が、var1が置換フィールドおよびAPIによって置き換えることはできませんが、私に奇妙なエラー –

答えて

0

def index(request):  
    var1 = Search.objects.latest('search_query').search_query 
    context = {'property': var1 } 
    return render(request, 'YOURVIEW', context) 

、その後ビューで辞書にアクセス:https://docs.djangoproject.com/en/1.11/intro/tutorial03/

{{ property.your_key}} 

は、Djangoのアプリケーション部3チュートリアルでより多くの情報を参照してください。

0

あなたがしようとしていることを理解するのは苦労しましたが、これは典型的な使用例です。クラウスD.さんのコメントどおり

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.all() 
    # do something with variable var1 

# another example 
def index(request, search_query): 
    # as you can notice I'm expecting the parameter search_query, so make sure that in urls.py you define it properly. 
    var1 = Search.objects.filter(search_query=search_query) 

編集:

また、あなたがfrom django.db.models import Q # filter using operators '&' or '|'を使用できるブール演算子を使用して便利な検索はあり

def index(request): 
    var1 = Search.objects.latest('search_query').search_query 
    # do something with variable var1 
+0

を与える私はこれを「VAR1」を交換したいです置き換え '' 'python user_profile = requests.get( 'https://api.github.com/users/ {0}')。 content = dict() 内容['user'] = user_profile.json() '' ' var1は置換フィールドで置き換えることはできません。 –

1

ドットを逃しています。

例:クエリセットを使用しての詳細については

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

乾杯 ヘンリー

関連する問題