如何在具有外键关系的模型中编写查询?

时间:2017-09-04 08:19:47

标签: django django-rest-framework django-views

class Categorie(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(max_length=2000)
    status = models.BooleanField(default=True)
    added_date = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
     return u'%s' % self.name


class GroupQuestion(models.Model):
    category = models.ForeignKey(Categorie, related_name='%(class)s_name_related', null=True)
    name = models.CharField(max_length=200)
    added_date = models.DateTimeField(auto_now_add=True)
    status = models.BooleanField(default=True)

    class Meta:
        verbose_name = 'Group of Questions'
        verbose_name_plural = 'Group of Questions'

    def __unicode__(self):
        return u'%s' % self.name


 class Question(models.Model):
    category = models.ForeignKey(Categorie, related_name='%(class)s_name_related', null=True)
    group = models.ForeignKey(GroupQuestion, related_name='%(class)s_name_related')
    name = models.TextField(max_length=200)
    added_date = models.DateTimeField(auto_now_add=True)
    status = models.BooleanField(default=True)
    #select_choice = models.CharField(max_length=5, choices=QUESTION_CHOICES, null=True)
    positive_answer = models.PositiveIntegerField()
    negative_answer = models.PositiveIntegerField()

   def __unicode__(self):
       return u'%s' % self.name

我有这三种模式。当我从我的API传递category_id时想要获得与该组相关的QuestionGroups和Question?

有点像这样

“数据”:[          {             ID:1             name = ABC             “题”:[                         {                           “ID”:1                           “名”:ABC                         }                         {                           “ID”:1                           “名”:ABC                         }                     ]                 }                {                   ID:1                   name = ABC                   “题”:[                          {                            “ID”:1                            “名”:ABC                          }                          {                            “ID”:1                            “名”:ABC                          }                      ]                  }   }

我是django的新手,有些人可以帮助我如何在视图中编写查询以及如何序列化数据。

1 个答案:

答案 0 :(得分:0)

您正在寻找nested serialization

您应该创建两个序列化程序。一个用于GroupQuestion模型,另一个用于Question模型。您将在QuestionSerializer 内部 GroupQuestionSerializer中使用,以执行嵌套序列化

serializers.py

from rest_framework import serializers

from .models import GroupQuestion, Question


# Serializer for the Question model
class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = ('id', 'name')


# Serializer for the GroupQuestion model
class GroupQuestionSerializer(serializers.ModelSerializer):
    question_name_related = QuestionSerializer(read_only=True, many=True)
    # The magic happens here ^
    # You use your QuestionSerializer inside your GroupQuestionSerializer
    # In order to serialize the related Questions for this GroupQuestion

    class Meta:
        model = GroupQuestion
        fields = ('id', 'question_name_related')

然后,假设您有一个简单的ListAPIView用于列出您的GroupQuestion条目。

views.py

from rest_framework import generics

from .models import GroupQuestion
from .serializers import GroupQuestionSerializer
# Import the serializer that we have just created


class GroupQuestionList(generics.ListAPIView):
    serializer_class = GroupQuestionSerializer

    def get_queryset(self):
        category_id = self.kwargs['category_id']
        category = generics.get_object_or_404(Categorie, id=category_id)

        return GroupQuestion.objects.filter(category=category)

此视图只会序列化所有您的GroupQuestion模型,这些模型与给定的Categorie相关id

最后,在您的网址中映射此视图,当您访问此端点时,您应该获得预期的结果。

urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^groups/(?P<category_id>[0-9]+)/$', views.GroupQuestionList.as_view(), name='group_question_list')
]

注意:我不确定question_name_related中的related_name模型QuestionGroupQuestion的有效abc