Django Sequence Returns an empty list

Hey guy I'm new to Django. I am using Rest API with Django to interact with my Android app. I have the data I need in the quest variable . Since there are several questions, I am using a filter instead of get.

This is my 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

      

This is my 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')

      

URL that is defined for display:    http://127.0.0.1:8000/mapers/   Exception type: KeyError Exception value: 'category_id'

when I ask for a specific category, it returns:    http://127.0.0.1:8000/mapers/2/   {"detail": "Not Found". }

The Model.py file looks like this:

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

      

I want to get all category related questions and there is a selection from the select module, why are all things in get_queryset.

Please tell me how to get all the data I need in the MapertablesViewSet class

Thanks in advance, if you want me to submit the complete project, just let me know and I will zip and upload to disk or something.

+3


source to share


2 answers


@Kevin Brown is right, you shouldn't worry about serializers or displaying anything by method get_queryset

, but the thing I noticed about your method get_queryset

is that you don't add any item to lists queryset

and querylist

. I give you the following idea:

    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

      



As for the url, make sure you pass category_id

as a parameter in the url pattern. Something like url(r'^mapers/(?P<category_id>\d+)/?'

if you don't use routers

for this. It would be nice if you could enter your URL definition here. Hope this helps you better understand how to proceed.

+1


source


You are returning an empty list from your method get_queryset

, so no objects are returned in the list view and pk

no specific object can be found.



In your method, get_queryset

you seem to be doing a lot of unrelated things, and they are probably contributing to this problem. You don't have to do serialization there, DRF will handle that for you later. And you have to do the filtering in the method filter_queryset

or pass it to DRF. You also cannot return responses from this method, only a request.

0


source







All Articles