Annotate a single model's object

Hi everyone!

I have a model Post:

class Post(model.Models):
    title = models.CharField(<some parameters>)
    body = models.TextField(<some parameters>)

In a create view I have an object created. But in response I want to add some field(s) which not in a model what usually may be done with annotation in QuerySet.
This is my current function looks like:

    def create_post(self, post_dto: PostNewDTO) -> PostNewDTO:
        """Creates new Post objects in Database"""
        logger.info("Creation of new Post object requested.")
        new_post = Post(
            profile_id=post_dto.profile_id,
            project_id=post_dto.project_id,
            body=post_dto.body,
            is_active=post_dto.is_active,
            image=post_dto.image,
        )
        # new tags {set} added, unpacked and saved
        if post_dto.tags is not None:
            new_post.tags.add(*post_dto.tags)
        new_post.save()
       return new_post

Is there a way to annotate a single model’s instance on ORM level without manually appending a response data? Something like new_post.annotate(some_field=value)

Please be more specific and detailed about what your ultimate objective is behind this question.

Include what you are looking for as the lifespan of this additional data element - is it temporary (exists for only the one view in which it’s created), or are you looking for it to be persistent?

Let me explain the idea more detailed:
I have an api view (POST). Request body parameters are passed to the service method from above which returns a newly created object. This object is passed to Serializer which returns a serialized data of that newly created object to a client as a response.
On the other hand I have a list view (for GET requests) which returns from API list of all objects but annotated with ‘likes_count’, ‘comments_count’ etc.
Once create view triggered I want to return newly created Post’s model instance but with additional fields which are not in a model class such as ‘likes_count’ and ‘comments_count’. Those fields will have some default values. Let’s say = 0.

Yes, you can dynamically add values to an instance of a model, in exactly the same way you can arbitrarily add any attribute to any object.

However, these additional attributes are not fields in the model, which means that any subsequent processing of that instance needs to specifically handle those attributes.

1 Like

Thank yor for a guidance. Will look at this way.