Home > Enterprise >  Getting related models in template
Getting related models in template

Time:03-06

I've got two models. I'm attempted to get a qs of jobs for a given review within my template

Models.py

    class Job(models.Model):
        employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, blank=True) 
        cart = models.ForeignKey(Cart, related_name="cartmodel",  on_delete=models.CASCADE, null=True, blank=True) 

    class Review(models.Model)
         cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None)

views.py

reviews = Review.objects.all()

template

{% for review in reviews %}
    {% for i in review.cart.job_set.all %}

        {{i.employee}}

    {% endfor %}
{% endfor %}

The code in my template isn't working. Any thoughts how to correctly build this set in my template ?

Thanks!

CodePudding user response:

Since you specified as related_name='cartmodel', that means you access the related Jobs with review.cart.cartmodel.all, but the related_name='cartmodel' is likely a misnomen: this is the name of the ForeignKey in reverse, so you might want to rename this to:

class Job(models.Model):
    employee = models.ForeignKey(
        Employee,
        on_delete=models.CASCADE,
        null=True,
        blank=True
    )
    cart = models.ForeignKey(
        Cart,
        related_name='jobs',
        on_delete=models.CASCADE,
        null=True,
        blank=True
    )

then you can thus render this with:

{% for review in reviews %}
    {% for i in review.cart.jobs.all %}
        {{ i.employee }}
    {% endfor %}
{% endfor %}

It is also strange that the foreign keys are (both) NULLable, this means that i.employee can be None, and thus not point to a real employee.

You can optimize querying by prefetching the cart and jobs with:

reviews = Review.objects.select_related('cart').prefetch_related('cart__jobs')
  • Related