Как отфильтровать дополнительную модель в DetailView? - PullRequest
2 голосов
/ 20 января 2020
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(), а затем фильтрую его в своем шаблоне. Просто подумайте, что есть лучший способ сделать это.

1 Ответ

2 голосов
/ 20 января 2020

Вы можете просто получить отношение в обратном порядке:

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)
        <b>context['rates'] = self.object.rate_set.all()</b>
        return context

Как говорится, здесь нет особой разницы для выполнения запроса в шаблоне, поскольку здесь есть только один объект, поэтому N + 1 проблема .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...