如何将所有ForeignKey和OneToOneField字段设置为raw_id_fields

For example I have this 3 fields as set_soal, soal and folder. I need to assign all of this fields into raw_id_fields into their admin.ModelAdmin without add manually per-single fields.

class DaftarSoal(TimeStampedModel):
    ....
    set_soal = ForeignKey(SetSoal, ...)
    soal = ForeignKey(Soal, ...)
    folder = ForeignKey(Folder, ...)

the basic way to enable raw fields inside the admin.ModelAdmin look like this;

@admin.register(DaftarSoal, site=admin_site)
class DaftarSoalAdmin(admin.ModelAdmin):
    raw_id_fields = ('set_soal', 'soal', 'folder')    # manually

screenshot 1

But, can I setup all that OneToOneField and ForeignKey fields automatically into raw_id_fields without add it manually? such as applying the class mixin, for example:

class CustomAdminMixin:
    raw_id_fields = ()

    def __init__(self):
        self.setup_raw_id_fields()

    def setup_raw_id_fields(self):
        # search all OneToOneField and ForeignKey fields.
        # and assign into variable `raw_id_fields` above.

并实施;

@admin.register(DaftarSoal, site=admin_site)
class DaftarSoalAdmin(CustomAdminMixin, admin.ModelAdmin):
    pass



@admin.register(AnotherModel, site=admin_site)
class AnotherModelAdmin(CustomAdminMixin, admin.ModelAdmin):
    pass
评论
cut
cut

You can inspect the model, and search through the fields for instances of ForeignKey, and add the name to the tuple, for example with:

from django.db.models import (ForeignKey, OneToOneField)

class CustomAdminMixin:
    raw_id_fields = ()

    def __init__(self, model, admin_site, *args, **kwargs):
        self.raw_id_fields = self.setup_raw_id_fields(model)
        super().__init__(model, admin_site, *args, **kwargs)

    def setup_raw_id_fields(self, model):
        return tuple(
            f.name
            for f in model._meta.get_fields()
            if isinstance(f, ForeignKey) or isinstance(f, OneToOneField)
        )

A OneToOneField is a subclass of a ForeignKey, so there is no need to make search for a OneToOneField.

点赞
评论