如何在Django管理页面(在formfield_for_foreignkey内部)中获取实际的对象ID? [英] How do I get the actual object id in a Django admin page (inside formfield_for_foreignkey)?

查看:290
本文介绍了如何在Django管理页面(在formfield_for_foreignkey内部)中获取实际的对象ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经解决了使用以下代码编辑对象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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆