Home > Software design >  Accessing a field from a model linked to another model with get_context_data()
Accessing a field from a model linked to another model with get_context_data()

Time:04-23

I have the following models in my Django app:

  • Model User
class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField('username', max_length=30, blank=True)
    email = models.EmailField('Adresse mail', unique=True)
    first_name = models.CharField('Prénom', max_length=30, blank=True)
    last_name = models.CharField('Nom', max_length=30, blank=True)
    date_joined = models.DateTimeField('date joined', auto_now_add=True)
    company = models.ForeignKey('Company', on_delete=DO_NOTHING, blank=True, null=True)
  • Model Company
class Company(models.Model):
    name = models.CharField(max_length=200, blank=False)
    transporters = models.ManyToManyField(Transporter, blank=True)
  • Model Transporter
class Transporter(models.Model):
    name = models.CharField(max_length=100)
    avatar = models.ImageField(blank=True, null=True)

  • Model Supplement
class Supplement(models.Model):
    transporter = models.ForeignKey(Transporter, on_delete=DO_NOTHING, blank=True, null=True)
    company = models.ForeignKey(Company, on_delete=DO_NOTHING, blank=True, null=True)
    header_row = models.IntegerField(blank=True)

Starting from the user, I would like to access the field header_row in get_context_data(). In my app, the user belongs to a company and the 'supplement' is attached to a Company.

Here's what I came with in views.py :

class UserSupplementView(TemplateView):

    model = User
    template_name = 'tool/try.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = self.request.user
        context['supplements'] = user.company.supplement.header_row
        print(context['supplements'])
        return context

But it's not working and I have the following error message:

'Company' object has no attribute 'supplement'

But if I go with context['supplements'] = user.company.supplement_set.all() , I can actually retrieve part of the data. Could you please help me to retrieve the header_row field?

CodePudding user response:

Since you are using .all() you then need to loop through the Queryset. If you need to get the header_row field you would need to do loop through the results first. You can do this in the view or in the template.

In the template:

{% for supplement in supplements %}
 {{ supplement.header_row }}
{% endfor %}

That should work in the template.

If you want to test to see if you're getting all the data, including the header_row without having to loop, use .first() instead of .all() in the view or .first in the template {% for supplement in supplements.first %}

This is based on you updating your query in the view to what you mentioned last user.company.supplement_set.all()

  • Related