簡體   English   中英

如何過濾DetailView中的附加模型?

[英]How to filter the additional model in DetailView?

class Source(models.Model):
    Name = models.CharField(max_length=150)`enter code here`
    Address = models.CharField(max_length=150)
    Office_Phone = PhoneField(blank=True, help_text='Office phone number')
    Main_Contact = models.CharField(max_length=150, blank=True, null=True)
    Contact_Email = models.EmailField(max_length=254, blank=True, null=True)
    Contact_Phone = PhoneField(blank=True, help_text='Main Contact phone number')
    Billing_Contact = models.CharField(max_length=150, blank=True, null=True)
    Billing_Email = models.EmailField(max_length=254, blank=True, null=True)
    Billing_Phone = PhoneField(blank=True, help_text='Billing Contact phone number')
    Notes = models.CharField(max_length=250, blank=True, null=True)

    def __str__(self):
        return self.Name

    def get_absolute_url(self):
        return reverse('sources-detail', kwargs={'pk': self.pk})


class Rate(models.Model):
    Source = models.ForeignKey(Source, on_delete=models.CASCADE)
    Report_Type = models.ForeignKey(ReportType, on_delete=models.CASCADE)
    Amount = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)

class SourceDetailView(DetailView):
    model = Source
    template_name = 'intake/source_detail.html'
    context_object_name = 'source'

    def get_context_data(self, *args, **kwargs):
        context = super(SourceDetailView, self).get_context_data(*args, **kwargs)
        context['rates'] = Rate.objects.all.filter(***not sure what to put here***)        
        return context

在模板中過濾它還是在視圖中進行過濾會更好? 如果我不過濾它並且只使用Rate.objects.all() ,我就能得到結果,然后我在我的模板中過濾它。 只是認為有更好的方法來做到這一點。

您可以反向獲取關系:

class SourceDetailView(DetailView):
    model = Source
    template_name = 'intake/source_detail.html'
    context_object_name = 'source'

    def get_context_data(self, *args, **kwargs):
        context = super(SourceDetailView, self).get_context_data(*args, **kwargs)
        context['rates'] = self.object.rate_set.all()
        return context

話雖如此,這里在模板中進行查詢沒有太大區別,因為這里只有一個對象,所以不存在N+1 問題

暫無
暫無

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

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