5

我有这两个模型和模型管理员。在可用主机用户列表中添加新主机时,只会出现未分配给另一台主机的主机用户。问题是如果我编辑一个已经创建的主机,它的实际主机用户 ID 也会被过滤,所以我想做的是排除当前分配的主机用户 ID。如何在从 hostuser 字段中排除当前 id 中指定?

我需要的语句写在 *

提前致谢

模型.py

class HostUser(models.Model):
    name = models.CharField(max_length=200)
    {..More Data..}

class Host(models.Model):
    {..More Data..}
    hostuser = models.ForeignKey(HostUser, blank=True, null=True)

管理员.py

class HostAdmin(admin.ModelAdmin):
    {..More Data..}
    def render_change_form(self, request, context, *args, **kwargs):
        list_names = Host.objects.values_list('hostuser__id', flat=True).exclude(hostuser__id=None).exclude(hostuser__id=**ACTUAL HOSTUSER_ID**)
        list_names = [int(ids) for ids in list_names]
        context['adminform'].form.fields['hostuser'].queryset = HostUser.objects.exclude(id__in=list_names)
        return super(HostAdmin, self).render_change_form(request, context, args, kwargs)
4

1 回答 1

5

(在问题编辑中回答。转换为社区 wiki 答案。请参阅将问题的答案添加到问题本身时的适当操作是什么?

OP写道:

使用 kwargs 解决,Modeladmin 如下所示:

def render_change_form(self, request, context, *args, **kwargs):
    try:
        list_names = Host.objects.values_list('hostuser__id', flat=True).exclude(hostuser__id=None).exclude(hostuser__id=kwargs['obj'].hostuser.id)
    except:
        list_names = Host.objects.values_list('hostuser__id', flat=True).exclude(hostuser__id=None)
    list_names = [int(ids) for ids in list_names]
    context['adminform'].form.fields['hostuser'].queryset = HostUser.objects.exclude(id__in=list_names)
    return super(HostAdmin, self).render_change_form(request, context, args, kwargs)
于 2015-02-08T18:05:25.340 回答