2015-07-19 70 views
3

你好蓋伊我是Django的新手。我使用Django的Rest API與我的android應用程序進行交互。 我有我需要的數據在可變任務。由於我有很多問題使用過濾器而不是get。Django序列化返回一個空列表

這是我Views.py:

class MapertablesViewSet(viewsets.ModelViewSet): 
    """ 
    API endpoint that allows groups to be viewed or edited. 
    """ 
    queryset = Mapertables.objects.all() 
    serializer_class = MapertablesSerializer 
    lookup_field = 'category_id' 

    def get_queryset(self): 
     #print self.kwargs['category_id'] 
     maps = Mapertables.objects.filter(category_id=self.kwargs['category_id']) 
     #queryset = list(maps) 
     #queryset = serializers.serialize('json',maps) 
     #print "AAAA ",queryset 
     i = 0 
     #quest ={} 
     queryset = [] 
     queslist = [] 
     for question in maps: 
      quest = {} 
      quest['question'] = question.question_id 
      #print 'qqqq ',question.question_id 
      #queryset = serializers.serialize('json',[question,]) 
      choices = Choice.objects.filter(question=question.question_id) 
      print choices 
      #aaa = chain(question,choices) 
      #print aaa 
      #queryset = serializers.serialize('json',[question,choices,]) 
      j = 0 
      for option in choices: 
       quest[j] = option.choice_text 
       j += 1 
      print 'data Here ',quest 
      #data Here {0: u'Highbury', 1: u'Selhurst Park', 2: u'The Dell', 3: u'Old Trafford', 'question': <Question: At which ground did Eric Cantona commit his "Kung Fu" kick ?>} 
      serializer_class = CoustomeSerializer(queryset, many=True) 
      print serializer_class.data 
      #[] 
      json = JSONRenderer().render(serializer_class.data) 
      print 'JSON',json 
      #[] 
      i += 1 

     queryset = queslist 
     serializer_class = CoustomeSerializer(queryset,many=True) 
     return queryset 
     #print "questions",queslist 
     #print "Ser ",ser.data 

這是我的serializers.py:被定義顯示

class MapertablesSerializer(serializers.HyperlinkedModelSerializer): 
    class Meta: 
     model = Mapertables 
     fields = ('question_id','category_id') 


class CoustomeSerializer(serializers.HyperlinkedModelSerializer): 
    #questions = MapertablesSerializer(source='question_id') 
    #choices = ChoiceSerializer(source='choice_text') 
    class Meta: 
     model = Question,Choice,Category 
     fields = ('choice_text','choice_text','choice_text','choice_text','question_id') 

網址: http://127.0.0.1:8000/mapers/ 異常類型:KeyError異常 異常值: 'category_id'

當我查詢它返回的特定類別時: http://127.0.0.1:8000/mapers/2/ { 「detail」:「Not found。」 }

Model.py文件如下:

from django.db import models 

# Create your models here. 
class Category(models.Model): 
    category_name = models.CharField(max_length=200,default='1') 
    def __str__(self): 
     return self.category_name 


class Question(models.Model): 
    question_text = models.CharField(max_length=200) 
    #category_name = models.ForeignKey(Category) 
    pub_date = models.DateTimeField('date published') 
    def was_published_recently(self): 
     return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 
    was_published_recently.admin_order_field = 'pub_date' 
    was_published_recently.boolean = True 
    was_published_recently.short_description = 'Published recently?' 
    def __str__(self): 
     return self.question_text 


class Mapertables(models.Model): 
    category_id = models.ForeignKey(Category) 
    question_id = models.ForeignKey(Question) 


class Choice(models.Model): 
    question = models.ForeignKey(Question) 
    choice_text = models.CharField(max_length=200) 
    votes = models.IntegerField(default=0) 
    def __str__(self): 
     return self.choice_text 

我希望得到有關類別的所有問題,並有選擇形成的選擇模塊,爲什麼在get_queryset所有的東西。

請告訴我怎麼走都在MapertablesViewSet類我需要

預先感謝您的數據,如果你要我送完整的項目只是讓我知道,我會做拉鍊,並將其上傳到開車什麼的。

+0

你看到quest和serializer_class的輸出,這是代碼打破。 –

回答

1

@Kevin布朗是正確的,你不應該擔心串行,或呈現的get_queryset方法什麼,但我在你的get_queryset方法注意到的事情是,你沒有任何項目追加到列表queryset,和querylist。我下面給你一個想法:

def get_queryset(self): 
     #print self.kwargs['category_id'] 
     maps = Mapertables.objects.filter(category_id=self.kwargs['category_id']) 
     i = 0 
     queryset = [] 
     for question in maps: 
      quest = {} 
      quest['question'] = question.question_id 
      choices = Choice.objects.filter(question=question.question_id) 
      print choices 

      j = 0 
      for option in choices: 
       quest[j] = option.choice_text 
       j += 1 
      print 'data Here ',quest 
      # Adding items to queryset list 
      queryset.append(quest) 
      i += 1 

     # You should have values here on queryset list 
     print queryset 

     return queryset 

至於URL,確保你傳遞category_id爲URL模式的參數。就像url(r'^mapers/(?P<category_id>\d+)/?',如果你不使用routers這個。如果你在這裏粘貼你的URL定義將會很好。那麼,我希望它能幫助你更好地瞭解如何繼續。

0

您正在返回get_queryset方法中的空列表,因此在列表視圖中沒有返回對象,並且pk也無法檢索到特定的對象。

你似乎在你的get_queryset方法中做了很多不相干的事情,他們可能是造成這個問題的原因。你不應該在那裏做任何序列化,DRF將在稍後爲你處理。你應該在filter_queryset方法中進行篩選,或者將它傳遞給DRF來完成。您也無法返回來自該方法的任何響應,僅返回一個查詢集。

+0

謝謝你的時間。 get_queryset中的內容是獲取所有類別的數據庫。我採取類別id並檢索問題。獲取問題的選擇。有沒有一個簡單的方法來做到這一點。如果有的話請提出建議真的謝謝你..而且我還會研究filter_queryset –