以下是我的模特:
class Owner():
last_name = models.CharField(max_length=30)
...
class Species():
species_code = models.CharField(max_length=10)
...
class Pet():
client = models.ForeignKey(Owner, related_name='pet_fk')
species = models.ForeignKey(Species)
....
我想列出所有的主人和他们的宠物。有些业主没有宠物,有些则有很多。
如果找到了宠物,我想注释一个额外的临时'对该动物的对象css_species_class
字段。该字段将返回“狗”字样。如果宠物模型的species_code是“CANINE”或“马匹”。如果' EQUINE'等。
'临时'由于网站是多语言的,因此需要字段,并且需要css_species_class
值来在模板中提取适当的字形图标。我无法直接使用存储的值,因此我需要插入一个特定值来匹配字形所期望的值。
类似的东西:
Owner: John Smith
Pet: Saag (css_species_class='dog')
Pet: Brinjal (css_species_class='cat')
Pet: Baji (css_species_class='dog')
Owner: Sue Smith
Pet: none
Owner: Clare Smith
Pet: Aloo (css_species_class='horse')
我的模板是这样的:
{% for owner in owners %}
<tr>
<td>{{ owner.first_name }} {{ owner.last_name }}</td>
<td> <!-- loop over pet objects -->
{% for pet in owner.pet_fk.all %}
<div>
....
<span class="glyphicons glyphicons-{{ pet.css_species_class }}"></span>
....
</div>
{% endfor pet %}
</td>
</tr>
{% endfor %}
所以,这是我第一次尝试解决方案:
class OwnerListView(ListView):
template_name = 'visitors/owner_list.html'
context_object_name = 'owners'
paginate_by = 50
def get_queryset(self):
owners_with_pets = Owner.objects.filter(pet_fk__isnull=False).prefetch_related('pet_fk').distinct()
# logic goes here to loop over pets
# and assign 'css_species_class' temp field
owners_without_pets = Owner.objects.filter(pet_fk__isnull=True).prefetch_related('pet_fk').distinct()
然后&#39;合并&#39;这两个查询集合在一起:
result_list = sorted(
chain(owners_with_pets, owners_without_pets),
key=attrgetter('last_name'))
return result_list
这个&#39;工作&#39;对于少数业主,但如果我用实数测试(大约4,000),我会得到太多的sql变量&#39;错误。
我最初尝试在一个查询中执行此操作(在决定将其分解为两个查询之前),但对于大量客户而言,这也失败了。
有人可以给我一些关于如何最好地接近这个的指导吗?非常感谢。
答案 0 :(得分:0)
尝试此代码,未经测试,但我认为它有效。
class Owner():
last_name = models.CharField(max_length=30)
...
class Species():
species_code = models.CharField(max_length=10)
...
class Pet():
# related_name is used for backward relation
# this will end up as owner."related_name" --> owner.pets
client = models.ForeignKey(Owner, related_name='pets')
species = models.ForeignKey(Species)
...
@property
def css_species_class(self):
# this could be anything you want eg: css_scecies_class
return self.species.species_code
class OwnerListView(ListView):
template_name = 'visitors/owner_list.html'
context_object_name = 'owners'
paginate_by = 50
def get_queryset(self):
# no need to check if onwner instance has pets if you chain them both back
return Owner.objects.prefetch_related('pets').all().distinct()
{% for owner in owners %}
<tr>
<td>{{ owner.first_name }} {{ owner.last_name }}</td>
<td> <!-- loop over pet objects -->
{% for pet in owner.pets %}
<div>
....
<!-- now we can access pet.css_species_class directly because we made it a property of pet class -->
<span class="glyphicons glyphicons-{{ pet.css_species_class }}"></span>
....
</div>
{% endfor pet %}
</td>
</tr>
{% endfor %}