简体   繁体   中英

Django model foreignkey queries

So i have this two models in 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)

So whenever a user "buys" a course, it is stored in UserCourse. I have a view where the system shows a list of all the courses the user has bought. This is the view code:

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)

I dont know where is the error and I cant seem to catch the exception (im using django with docker)

tl;dr

Something like this should work.

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

Explanation

There are multiple ways to do this, but one way would be to first get all the UserCourse objects for the current user:

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

Then, for each UserCourse object, get the related Course :

user_courses = [x.course for x in usercourse_objects]

Now, the second line causes N database queries (one for each time we follow the course foreign key relation. To prevent this, the first line can be changed to:

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

This pre-populates the course attribute of the UserCourse objects. More info about select_related() can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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