Django模型foreignkey查询

时间:2017-03-08 00:22:09

标签: python django django-models

所以我在django中有这两个模型:

class Course(models.Model):

    def get_image_path(self, filename):
        return os.path.join('courses', str(self.slug), filename)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Course, self).save(*args, **kwargs)

    name = models.CharField(max_length=255, verbose_name="Nombre")
    description = models.CharField(max_length=255,       verbose_name="Descripción")
    price = models.DecimalField(max_digits=12,decimal_places=2, verbose_name="Precio")
    slug = models.SlugField(blank=True, max_length=255)
    icon_img = models.ImageField(upload_to=get_image_path, blank=True, null=True, verbose_name="Imagen")
background_color = ColorField(default="#026085")


    class Meta:
        verbose_name = "curso"
        verbose_name_plural = "cursos"

class UserCourse(models.Model):
    user = models.ForeignKey(User)
    course = models.ForeignKey(Course)

因此,每当用户“购买”课程时,它都会存储在UserCourse中。我有一个视图,系统显示用户购买的所有课程的列表。这是视图代码:

def user_course_list_view(request, username):
    context_dict = {}
    try:
        user_courses = UserCourse.objects.filter(user=request.user).course_set
        context_dict['courses'] = user_courses
        context_dict['heading'] = "Mis cursos"
    except:
        context_dict['courses'] = None
        context_dict['heading'] = "Mis cursos wey"
    return render(request, 'courses/course_list.html',  context=context_dict)

我不知道错误在哪里,我似乎无法捕获异常(我使用django和docker)

1 个答案:

答案 0 :(得分:2)

TL;博士

这样的事情应该有效。

usercourse_objects = UserCourse.objects.filter(user=request.user).select_related('course')
user_courses = [x.course for x in usercourse_objects]

解释

有多种方法可以做到这一点,但一种方法是先为当前用户获取所有UserCourse个对象:

usercourse_objects = UserCourse.objects.filter(user=request.user)

然后,对于每个UserCourse对象,获取相关的Course

user_courses = [x.course for x in usercourse_objects]

现在,第二行导致N个数据库查询(每次我们遵循course外键关系时一个。为了防止这种情况,第一行可以更改为:

usercourse_objects = UserCourse.objects.filter(user=request.user).select_related('course')

这会预先填充UserCourse对象的course属性。有关select_related()的更多信息,请访问here