如何在 Django 管理页面(在 formfield_for_foreignkey 内)中获取实际的对象 ID? [英] How do I get the actual object id in a Django admin page (inside formfield_for_foreignkey)?
问题描述
我已经解决了使用此代码编辑对象 id 的问题:
I 've already solved the problem of getting the object id being edited using this code:
class CompanyUserInline(admin.StackedInline):
"""
Defines tabular rules for editing company users direct in company admin
"""
model = CompanyUser
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "user":
users = User.objects.filter( Q(is_superuser=False) )
query = Q()
for u in users:
aux = CompanyUser.objects.filter(user=u)
if aux.count() == 0:
query |= Q(pk=u.id)
try:
cpu = CompanyUser.objects.filter(company__id=int(request.path.split('/')[4]))
for p in cpu:
query |= Q(pk=p.user.id)
except:
pass
kwargs["queryset"] = User.objects.filter(query).order_by('username')
return super(CompanyUserInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
但是,int(request.path.split('/')[4]) 真的很丑.我想知道如何从 Django AdminModel 获取 id.我确定它在里面的某个地方,有人知道吗?
But, the int(request.path.split('/')[4]) is really ugly. I want to know how I get the id from the Django AdminModel. I'm sure it's somewhere inside it, anyone knows?
先谢谢你!;D
推荐答案
据我所知,通过 formfield_for_...
方法访问当前实例是不可能的,因为它们会只为单个字段实例调用!
As far as i know it is not possible to access the current instance through the formfield_for_...
-methods, because they will only be called for a single field instance!
在这个逻辑中你可以访问整个实例/表单的一个更好的点是 get_form
.您还可以在那里覆盖表单字段的查询集!
A better point to hook into this logic where you can access the whole instance/form would be get_form
. You can also overwrite a form field's queryset there!
这篇关于如何在 Django 管理页面(在 formfield_for_foreignkey 内)中获取实际的对象 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!