Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disallow Django self-referential foreign key to point to self object

I have a regular self-referential foreign key:

idol = models.ForeignKey("self", on_delete=models.CASADE)

The admin page allows me to choose the the same object id. How can I prevent the django admin form from showing it?

like image 434
iTayb Avatar asked Dec 24 '22 23:12

iTayb


1 Answers

You can override formfield_for_foreignkey in your subclass of ModelAdmin class.

The formfield_for_foreignkey method on a ModelAdmin allows you to override the default formfield for a foreign keys field.

Parent object id can be saved in change_view method:

class IdolAdmin(admin.ModelAdmin):
    def change_view(self, request, object_id, form_url='', extra_context=None):
        self.object_id = object_id
        return super(IdolAdmin, self).change_view(
            request, object_id, form_url, extra_context=extra_context,
        )

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "idol":
            kwargs['queryset'] = Idol.objects.exclude(pk=self.object_id)
        return super(IdolAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs)
like image 179
ndpu Avatar answered May 20 '23 19:05

ndpu