django-ddp
django-ddp copied to clipboard
Property serialization
I mentioned this in my issue I submitted: I'm not sure this is how you would implement this, or if even it's useful to anyone else, but I wanted to be able to apply a decorator to model method to flag it as a serializable property. These are sent along with the serialized model fields to the client.
To avoid conflict with other uses of the python property decorator, I created a ddp_property decorator that adds an attribute the method that marks it to be serialized. That bit is checked at the end of the serialize method.
I didn't have any luck receiving related data or annotated data through my subscriptions, so this was one solution. If there is a better way, please let me know. Thanks!
Thanks for the contribution! I like the concept, but I'm undecided on the implementation. Can you explain why this is preferred over having a common serialization method?
Yeah, I'm not sure. I assumed there was a better way to accomplish this. I posted this as an issue/question before, assuming I was being dumb and missing something obvious.
I found that related objects only contain the ID of a related object, which would require me to look them up separately. I became accustomed to Django providing access to the entire related model, so I was trying to accomplish something similar in a single database pull. Am I missing something with this? Can we already pull down the values in related objects, or do I need to get them separately?
If I remember the code right, the serializer only handles the model fields and F expressions. I did try to annotate the query with related model values using F expressions, but it failed to serialize it in api.py. As a workaround, I just decided I would like to be able to decorate a model method and then have the serializer pick up the value it returns and append it to the payload going down to the client. This also allowed me to create properties that are accessible at the client-side as well.
With Django, I often use model methods as properties so I can reference them in the template or view easily. For example, how Django uses get_full_name on User model. This new decorator allowed for me to do this as well, so I thought it may be useful for calculated fields or similar.
Just after I posted my reply, I think I see something in the serialize method in api.py that I simply missed before. It looks like if we use select_related to define specific fields from the related model, they'll get serialized with the rest. Is that right?
If that's the case, I knew I was just missing something simple. Ugh...
@tysonclugg - did I understand the use of select_related in this case? And if so, could the property I created still be useful for calculated or dynamic "fields" that aren't a part of the core model or related model?