[Answered ]-Filter queryset accouring to related objects in django

1๐Ÿ‘

I would create a special ForeinKey field to mark the fields.

class PermissionForeignKey(models.ForeignKey):
    # we only use this class to mark the field
    pass

# you can add lru_cache here to speed up
# you could also move this to the model as @classproperty
def perm_fk_fields(model):
    fk_fields = []
    for field in model._meta.get_fields():
        if isinstance(field, PermissionForeignKey):
            fk_fields.append(field)
            fk_model_fields = perm_fk_fields(field.remote_field.model)
            if fk_model_fields:
                fk_fields.append([field, fk_model_fields])

    return fk_fields

# in your model
class B(models.Model):
    # the model fields
    a = PermissionForeignKey(A,on_delete=Model.CASCADE)

๐Ÿ‘คrabbit.aaron

Leave a comment