【问题标题】:Populating json from multiple django models从多个 django 模型填充 json
【发布时间】:2020-05-10 18:00:25
【问题描述】:

我有以下 2 个 Django 模型,LessonsUserLessons

Lessons 将由管理员创建,UserLessons 基本上是在用户使用Lessoncompleted 进行时,Lesson 由外键链接。 UserLesson 不一定包含 Lesson 条目,直到用户真正开始使用该特定条目。

在构建 API(使用 DRF)时,我需要列出所有课程的完整列表 - 很简单。 LessonList = Lesson.objects.all().values('id', 'title')

这会返回

[
    {
        "id": 1,
        "title": "Lesson 1"
    },
    {
        "id": 2,
        "title": "Lesson 2"
    },
    {
        "id": 3,
        "title": "Lesson 3"
    }
]

但是,我需要能够将它与 UserLesson 合并(例如,当前返回的 UserLessonList = UserLesson.objects.filter(user=request.user).values('id', 'lesson__id', 'completed')

[
    {
        "id": 2,
        "lesson__id": 1,
        "completed": true
    },
    {
        "id": 3,
        "lesson__id": 2,
        "completed": true
    }
]

理想情况下,它应该返回数据库中的所有课程以及完整的值,如果数据库中不存在该特定课程,则默认为 completed: false

有什么建议吗?

编辑:

观看次数

class LessonList(APIView):

    permission_classes = (IsAuthenticated,)

    def get(self, request):

        LessonList = Lesson.objects.all().values('id', 'title')
        UserLessonList = UserLesson.objects.filter(user=request.user).values('id', 'lesson__id', 'completed')





        return Response(LessonList)

型号

class Lesson(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    title = models.CharField(max_length=250, verbose_name=u'Title')
    slug = models.SlugField(null=True, blank=True, help_text='eg, lesson-1-whats-up')
    published = models.BooleanField(default=False)

    def __str__(self):
        return(self.title)

class UserLesson(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, null=True)
    completed = models.BooleanField(default=False)

    def __str__(self):
        text = str(self.lesson.title)
        return(text)

【问题讨论】:

  • 请添加您的代码:序列化程序和视图集
  • 我没有序列化器,但添加了模型和视图。
  • 但是您编写了构建 API(使用 DRF)。在这种情况下你如何使用 Django Rest Framework
  • 我认为在这种情况下这并不重要。
  • 这真的很重要。为什么不使用序列化程序来解决这个问题?

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


【解决方案1】:

您应该使用ModelViewSet 和序列化程序。正是ModelSerializer。像这样的:

class LessonSerializer(serializers.ModelSerializer):
    completed = serializers.SerializerMethodField()
    class Meta:
        model = Lesson
        fields = ['id', 'title', 'completed']

   def get_completed(self, obj):
        user = self.context.get('request').user
        return UserLesson.objects.filter(user=user, lesson=obj, completed=True).exists()

class LessonViewSet(viewsets.ModelViewSet):
    queryset = Lesson.objects.filter(published=True)
    serializer_class = LessonSerializer
    permission_classes = [IsAuthenticated]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-04
    • 2016-02-05
    • 2018-12-22
    • 2012-04-20
    • 1970-01-01
    • 2016-05-17
    • 2012-12-23
    • 2021-10-05
    相关资源
    最近更新 更多