Python 从多个django模型填充json
我有以下两种Django型号,Python 从多个django模型填充json,python,django,filter,django-rest-framework,django-views,Python,Django,Filter,Django Rest Framework,Django Views,我有以下两种Django型号,Lessons和UserLessons 课程将由管理员创建,用户课程基本上是当用户正在进行课程或完成课程时,通过外键链接UserLesson不一定包含Lesson条目,直到用户实际从该特定条目开始 在构建API(使用DRF)时,我需要列出所有课程的完整列表-很简单。 LessonList=Lesson.objects.all().values('id','title') 这是回报 [ { "id": 1, "title": "
Lessons
和UserLessons
课程
将由管理员创建,用户课程
基本上是当用户正在进行课程
或完成
课程时,通过外键链接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"
}
]
但是,我需要能够将其与当前返回的UserLessonList=UserLessonList=UserLesson.objects.filter(user=request.user)值('id','lesson\uu id','completed')合并
[
{
"id": 2,
"lesson__id": 1,
"completed": true
},
{
"id": 3,
"lesson__id": 2,
"completed": true
}
]
理想情况下,它应该返回数据库中的所有课程以及完成的值,如果特定课程在数据库中不存在,则默认为completed:false
有什么建议吗
编辑:
观点
模型
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)
您应该使用和序列化器。确切地说。类似于以下内容:
class LessonSerializer(serializers.ModelSerializer):
已完成=序列化程序。SerializerMethodField()
类元:
模型=课程
字段=['id'、'title'、'completed']
def get_完成(自身、obj):
user=self.context.get('request')。user
返回UserLesson.objects.filter(user=user,lesson=obj,completed=True).exists()
类LessonViewSet(viewset.ModelViewSet):
queryset=Lesson.objects.filter(published=True)
serializer\u class=LessonSerializer
权限\u类=[IsAuthenticated]
请添加您的代码:Serializer和ViewSets我没有Serialiser,但添加了模型和视图。但是您编写了一个API(使用DRF)。在这种情况下,如何使用Django Rest Framework我认为在这种情况下并不重要。这真的很重要。为什么不使用Serializer来解决这个问题?
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)