Ad

How To Create A Custom Function Inside Django Model?

I have a django model

class UserInfluencerGroupList(models.Model):
    list_name = models.CharField(max_length=255)
    influencers = models.ManyToManyField(Influencer, blank=True)
    user = models.ForeignKey(MyUser, on_delete = models.CASCADE)

    def __str__(self):
        return self.list_name

and my views function is:

def get_lists(request,user_email):
    """Get all the lists made by user"""
    try:
        user_instance = MyUser.objects.get(email=user_email)
    except MyUser.DoesNotExist:
        return HttpResponse(json.dumps({'message':'User not found'}),status=404)

    if request.method == 'GET':

        influencers_list = UserInfluencerGroupList.objects.all().order_by('id').filter(user=user_instance)
        influencers_list = serializers.serialize('json',influencers_list, fields =['id','influencers','list_name'], indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True)

        return HttpResponse(influencers_list,content_type='application/json',status=200)
    else:
        return HttpResponse(json.dumps({'message':'No lists found'}), status=400)

Apart from the usual data from list I also want to calculate the total_followers, total_likes and total_comments of each influencer in the list. The influencer model has fields for total_likes, comments and followers.

How should I write a function to calculate and display it along with all the other data that the list is returning

Ad

Answer

You should consider to use Django Rest Framework if you want to return a json of your own choice or/and if you're about to create your own rest api.

Alternative is to create the json all manually, i.e build the dictionary and then use json.dumps.

(If you really want to go "manual" see answer Convert Django Model to dict)

The django serializers does not support what you want to do:

option for serializing model properties (won't fix)

Quote for not fixing: "I'm afraid I don't see the benefit of what you are proposing. The serialization framework exists for the easy serialization of Django DB-backed objects - not for the arbitrary serialization of _any_ object, and derived properties like the ones you are highlighting as examples don't add anything to the serialized representation of a DB-backed object..."

Ad
source: stackoverflow.com
Ad