Django 管理更改列表以显示空外键(向后)
假设两个模型有一个标准的ForeignKey,例如:
Company(models.Model):
name = models.CharField('Nome', max_length = 255)
...
Ticket(models.Model):
company = ForeignKey(Company)
...
-- Update
在这个例子中,我的数据库中已经有很多公司,但没有Ticket。考虑到这一点,我的概念可能是错误的。但无论如何,我们开始......
在应用程序的 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])
我怎样才能进行这样的查询?
好吧...希望我现在已经足够清楚了。
Assume a standard ForeignKey for two models, like:
Company(models.Model):
name = models.CharField('Nome', max_length = 255)
...
Ticket(models.Model):
company = ForeignKey(Company)
...
-- Update
In this example, I have a lot of companies already in the database, but no Ticket. Considering this, I might be wrong in concept. But here we go anyway...
In admin.py of the app:
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])
How can I make a query like this?
Well... hope I was clear enough now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你有没有尝试过:
Have you tried:
根据您的评论进行更新:
要在管理中显示此内容,
ModelForm
ModelForm
中包含一个新的ModelChoiceField
以其中,您传递相关查询集和 Company 模型。ModelAdmin
中,传递表单的参数 - 上面创建的ModelForm
。ModelForm
上的保存
并执行操作。Update, based on your comment:
To display this in the admin,
ModelForm
, for this modelModelForm
Include a newModelChoiceField
to which, you pass the relevant queryset and theCompany
model.ModelAdmin
for this model, pass the argument for the form - theModelForm
created above.save
on the TicketModelForm
and do.我找到的解决方案:
在 urls.conf 中,添加模式:
然后,在 admin_views.py 中,创建 Ticket_list_result 方法
并在“admin/view_template.html”视图中列出这些结果:
The solution I found:
In urls.conf, add the pattern:
Then, in admin_views.py, create the ticket_list_result method
And list these results in the view on "admin/view_template.html":