1

I have three tables user, Profile and booking. Profile and booking table have foreign key with user table. Profile and Booking table are not directly linked. In BookingList view i want to access the profile data is it possible if yes how i can i do this.

models.py

class Profile(models.Model):
    uid = models.UUIDField(unique=True, editable=False, default=uuid.uuid4)
    name = models.CharField(max_length=100, unique=True)
    contact_person = models.CharField(max_length=100)
    mobile = models.CharField(max_length=15)
    email = models.CharField(max_length=40)

    created_by = models.ForeignKey(User, on_delete=models.PROTECT)
    profile_status = models.BooleanField(default=False)

    def __str__(self):
        return self.name

class Booking(models.Model):
    port_of_loading = models.ForeignKey(LoadPort, on_delete=models.PROTECT)
    port_of_discharge = models.ForeignKey(DestinationPort, on_delete=models.PROTECT)

    equipment_type = models.CharField(max_length=10, choices=CONT_TYP)
    quantity = models.IntegerField()
    pick_up_date = models.DateField(null=True, blank=True)
    hand_over_date = models.DateField(null=True, blank=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(User, on_delete=models.PROTECT)

    def __str__(self):
        return self.port_of_loading

views.py

class BookingList(LoginRequiredMixin, ListView):
    model = Booking
    template_name = 'documentation/details_booking.html'
    context_object_name = 'all_bk'

    def get_queryset(self):
        queryset = super(BookingList, self).get_queryset().order_by('-pk')
        return queryset

In template i want to access the profile.name

{% for item in all_bk %}
  <tr>
    <td>{{ item.created_by.profile.name }}</td>
  </tr>
{% endfor %}
Sachin Singh
  • 607
  • 4
  • 22
  • 2
    Additional to what Iain wrote, you can have a look at related_name: https://stackoverflow.com/questions/2642613/what-is-related-name-used-for-in-django – Joey Coder Dec 23 '19 at 07:26

1 Answers1

1

There can be multiple profiles created by a user so you will have to loop over them

{% for item in all_bk %}
  {% for profile in item.created_by.profile_set.all %}
    {{ profile.name }}
  {% endfor %}
{% endfor %}
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50