簡體   English   中英

在 Django 詳細視圖模板中顯示外鍵信息

[英]Display foreign key info within Django Detail View Template

正如標題所說,我有一個通過 Django 模板呈現的詳細視圖。 我有一個外鍵,我也想在該詳細視圖中顯示它,但我無法讓它工作。 我已經嘗試了一切,但我得到的只是基本的詳細視圖模板,沒有外鍵信息。 任何幫助將不勝感激。

這是我到目前為止所得到的:

楷模:

class Cust(models.Model): #this is the main model
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False)
    email = models.CharField(max_length=200)
    firstName = models.CharField(max_length=200)
    lastName = models.CharField(max_length=200)
    watchmanSlug = models.CharField(max_length=200, unique=True)
class Watchman(models.Model):
    group = models.ForeignKey(Cust, on_delete=models.CASCADE,to_field='watchmanSlug', 
    related_name='watchman_group_slug')
    uid = models.CharField(max_length=500)
    computer_name = models.CharField(max_length=500)
    computer_url = models.CharField(max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

意見

class CustomerDetailView(DetailView):
    model = Cust
    template_name = 'cust/cust_detail.html'
    
    def get_context_data(self, ** kwargs):
        context = super(CustomerDetailView, self).get_context_data( ** kwargs)
        context['computer_name'] = Watchman.objects.all()
        
        return context

詳細模板


                     <tbody>
                        <ul>
                          {% for p in watchman_group_slug.all %}
                          <li>{{ watchman.computer_name }}</li>
                          {% endfor %}
                
                      </ul>
                      </tbody>

您可以通過以下方式訪問相關的Watchman對象:

<tbody>
  <ul>
    {% for p in object.watchman_group_slug.all %}
      <li>{{ p.computer_name }}</li>
    {% endfor %}
  </ul>
</tbody>

所以使用object. watchman_group_slug.all object. watchman_group_slug.allp.computer_name

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM