Django - Get object id in render_change_form (Mode

2019-04-15 05:55发布

问题:

I have these two models and modeladmin. When adding a new host in the list of available hostuser only appear hostusers that are not assigned to another host. The issue is if I edit an already created host its actual hostuser id is also filtered so I want to do is to exclude hostuser id that is currently assigned. How I can specify in the exclude the current id from the hostuser field?

The statement that I need is written between *

Thanks in advance

Models.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)

Admin.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)

回答1:

(Answered in a question edit. Converted to a community wiki answer. See What is the appropriate action when the answer to a question is added to the question itself? )

The OP wrote:

Solved using kwargs, the Modeladmin looks like this:

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)