简体   繁体   English

Django序列化返回一个空列表

[英]Django Serialization Returns an empty list

Hello Guy I'm a newbie to Django. Hello Guy我是Django的新手。 Im using Rest API with Django to interact with my android application. 我使用Rest API与Django与我的Android应用程序进行交互。 I have the data I need in variable quest . 我有变量任务所需的数据 Since there are multiple questions I'm using filter instead of get. 由于有多个问题我使用过滤器而不是get。

This is my Views.py: 这是我的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: 这是我的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 to show: http://127.0.0.1:8000/mapers/ Exception Type: KeyError Exception Value: 'category_id' 定义为显示的URL: http//127.0.0.1 :8000 / mapers / Exception类型:KeyError异常值:'category_id'

when I query for a specific category it returns: http://127.0.0.1:8000/mapers/2/ { "detail": "Not found." 当我查询特定类别时,它返回: http//127.0.0.18000 / mapers/2 / {“detail”:“未找到”。 } }

Model.py file is as follows: 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

I want to get all questions related to category and there choices form the choices module that why all the stuff in get_queryset. 我想获得与类别相关的所有问题,并且选择模块中的选项可以解释为什么get_queryset中的所有内容。

Please tell me how to get all the data required for me in MapertablesViewSet class 请告诉我如何在MapertablesViewSet类中获取我所需的所有数据

Thank You in advance if you want me to send the complete project just let me know and I will make zip and upload it to a drive or something. 如果您希望我发送完整的项目,请提前告知我,我会提前感谢您,并将其上传到驱动器或其他内容。

@Kevin Brown is right you shouldn't worry about the serializers, or rendering anything on the get_queryset method, but a thing I noticed in your get_queryset method is that you don't append any item to the lists queryset , and querylist . @Kevin布朗是正确的,你不应该担心串行,或呈现的任何get_queryset方法,但我在你注意到的事情get_queryset方法是,你没有任何项目追加到列表queryset ,和querylist I'm giving you an idea below: 我在下面给你一个想法:

    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 to the URL, be sure you are passing the category_id as a parameter on the URL pattern. 对于URL,请确保将category_id作为URL模式的参数传递。 Something like url(r'^mapers/(?P<category_id>\\d+)/?' , if you are not using routers for this. It would be good if you paste here your URLs definition. Well, I hope it helps you to have a better idea how to continue. 有点像url(r'^mapers/(?P<category_id>\\d+)/?' ,如果你没有使用routers 。如果你在这里粘贴你的URL定义会很好。嗯,我希望它可以帮助你更好地了解如何继续。

You are returning an empty list from your get_queryset method, so no objects are being returned in the list view and a specific object cannot be retrieved by the pk . 您将从get_queryset方法返回一个空列表,因此列表视图中不返回任何对象,并且pk无法检索特定对象。

You appear to be doing a lot of unrelated things in your get_queryset method, and they are probably contributing to this issue. 您似乎在get_queryset方法中执行了许多不相关的操作,并且它们可能会导致此问题。 You shouldn't be doing any serialization there, DRF will handle that for you later. 您不应该在那里进行任何序列化,DRF将在以后为您处理。 And you should be doing filtering in the filter_queryset method, or passing that off to DRF to do. 你应该在filter_queryset方法中进行过滤,或者将其传递给DRF来做。 You also can't return any responses from that method, only a queryset. 您也无法从该方法返回任何响应,只返回查询集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM