gpt4 book ai didi

python - 如何过滤DetailView中的附加模型?

转载 作者:行者123 更新时间:2023-12-04 10:43:41 25 4
gpt4 key购买 nike

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

在模板中过滤它还是在 View 中进行过滤会更好?如果我不过滤它而只使用 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问题。

关于python - 如何过滤DetailView中的附加模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59819032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com