Home > OS >  Django - model class with non-persistent attribute that should be refreshed on each call
Django - model class with non-persistent attribute that should be refreshed on each call

Time:08-09

My User class looks like :

class User(AbstractBaseUser, SafeDeleteModel, PermissionsMixin):
    UNKNOWN = 'Unknown'

    id = models.AutoField(primary_key=True)
    email = models.EmailField(unique=True)
    default_organization = models.ForeignKey(to='Organization', on_delete=models.SET_NULL, null=True,
                                             related_name='default_organization', blank=True)

    organizations = models.ManyToManyField(to='Organization', through='UserOrganizationMembership',
                                           related_name='users', blank=True)

So a user can be a part of multiple organisations. However, each time he logs in, he must log in through ONE organisation. Now I have two kinds of orgs present - internal, client I have some telemetry setup for my application and the idea is that i want to not send any telemetry for internal orgs. I want to create an attribute in the /users api that returns this flag (flag depends on both the user and the account he logs in through).

My view class looks like this:

class UsersViewSet(UpdateModelMixin,
                   ListModelMixin,
                   GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserDetailSerializer

    def get_serializer_context(self):
        context = super().get_serializer_context()
        #self.request.user.is_telemetry_enabled =should_send_event(self.request.user, self.request.tenant.is_internal)
        context.update({"request": self.request})

        return context

    def get_permissions(self):
        permission_classes = [IsStaff] if self.action in ('list',) else [CanEditUser]
        return [permission() for permission in permission_classes]

What I've looked at :

  1. adding a field in model class and setting it in the get_serializer_context. Doesn't work because adding a field in model makes it a class variable, not per instance. second, it still didn't show up in the /users response.
  2. setting this as a property in models/users.py. Doesn't work because for setting a property the only argument allowed is self and my flag depends on self as well as which account self is logged in through. This information is present in the req context for me.

tldr : I want my GET /users (mapped to UsersViewSet) endpoint to return an additional param that is calculated every time the endpoint is hit. Currently, it returns the model picked directly from the db.

How do I achieve this? I'm fairly new to django/python

CodePudding user response:

you can add the calculated field in "UserDetailSerializer" class where you can calculate the value from where ever you want, such as session.

  • Related