假设两个模型的标准ForeignKey,例如:
Company(models.Model):
name = models.CharField('Nome', max_length = 255)
...
Ticket(models.Model):
company = ForeignKey(Company)
...
- 更新
在这个例子中,我有很多公司已经在数据库中,但没有Ticket。考虑到这一点,我的概念可能是错的。但无论如何我们走了......
在app的admin.py中:
class TicketAdmin(admin.ModelAdmin):
# ...
def queryset(self,request):
# ...
# This gives me the base I need: Companies without tickets
companies = Company.objects.annotate(n = Count('ticket')).filter(n = 0)
# But as the Ticket objects don't exist for a Company, I can't get them by a standard filter like:
Ticket.objects.filter(company__in = [o.id for o in companies])
如何进行这样的查询?
嗯......希望我现在已经足够清楚了。
答案 0 :(得分:1)
你试过了吗?
Company.objects.filter(ticket_set=None)
答案 1 :(得分:1)
Company.objects.annotate(tickets=Count('ticket')).filter(tickets=0)
根据您的评论进行更新:
要在管理员中显示,
ModelForm
ModelForm
中添加新的ModelChoiceField
,您可以传递相关的查询集和Company
模型。ModelAdmin
中,传递表单的参数 - 上面创建的ModelForm
。save
上的ModelForm
并执行此操作。答案 2 :(得分:1)
我发现的解决方案:
在urls.conf中,添加模式:
(r'^main/ligacao/$', 'main.admin_views.ticket_list_result')
然后,在admin_views.py中,创建ticket_list_result方法
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.db.models import Count
def ticket_list_result (request):
# ... parses, fetches, etc...
# Get companies without tickets
companies = Company.objects.annotate(n = Count('ticket')).filter(n = 0)
results = list()
for c in companies:
# Get tickets for the company
tickets = Ticket.objects.filter(company = c.id)
# Construct a dict to return to the view
results.append({
'company': c,
# ... any other desired info
})
return render_to_response(
"admin/view_template.html",
{'results' : results },
RequestContext(request, {}),
)
并在“admin / view_template.html”视图中列出这些结果:
{% block result_list %}
<table cellspacing="0" id="result_list">
<thead>
<tr>
<th>Company</th>
<!-- other columns -->
</tr>
</thead>
<tbody>
{% for r in results %}
<tr class="{% cycle 'row1' 'row2' %}">
<th>{{ r.company }}</th>
<!-- other company info -->
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}