如何从另一个与用户表django具有外键关系的表中获取数据?

时间:2019-12-23 07:18:23

标签: django django-models django-templates django-views

我有三个表的用户,个人资料和预订。配置文件和预订表具有与用户表的外键。个人资料和预订表未直接链接。在BookingList视图中,我想访问个人资料数据,如果可以,我该怎么做。

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

在模板中,我要访问个人资料。名称

{% for item in all_bk %}
  <tr>
    <td>{{ item.created_by.profile.name }}</td>
  </tr>
{% endfor %}

1 个答案:

答案 0 :(得分:1)

用户可以创建多个配置文件,因此您必须遍历它们

{% for item in all_bk %}
  {% for profile in item.created_by.profile_set.all %}
    {{ profile.name }}
  {% endfor %}
{% endfor %}