django ListView query_set代码缩写

时间:2018-02-05 03:43:25

标签: python django listview inner-join django-queryset

  

代码为

models.py

class Firm(models.Model):
    name = models.CharField(unique=True, max_length=50, verbose_name="Firma Adı")
    slug = models.SlugField(unique=True, editable=False, max_length=50)


class Worksite(models.Model):
    firm = models.ForeignKey('Firm', verbose_name='Firma', related_name="worksites", on_delete=models.CASCADE)
    name = models.CharField(unique=True, max_length=50, verbose_name="Şantiye Adı")
    slug = models.SlugField(unique=True, editable=False, max_length=50)


class Subcontractor(models.Model):
    worksite = models.ForeignKey('Worksite', on_delete=models.CASCADE)
    firm = models.ForeignKey('Firm', related_name="subcontractors", on_delete=models.CASCADE)
  

查询集代码可以写得更短吗?

views.py

class SubcontractorListView(ListView):
    template_name = 'firm/subcontractor_list.html'
    context_object_name = "firms"
    def get_queryset(self):
        ws = self.request.user.firm.worksites.values_list('id', flat=True)
        ss = Subcontractor.objects.values_list('firm_id', flat=True).filter(worksite_id__in=ws)
        return Firm.objects.filter(id__in=ss)
  

你有不同的短解决方案吗?

模板

{% for firm in firms %}
    <div class="btn btn-outline-secondary text-left button">{{ firm }} </div>
{% endfor %}

0 个答案:

没有答案