Oana Andone
Oana Andone

Reputation: 711

django retrieving objects, empty values

I use Profile.objects.values('id', 'avatar') to retrieve objects from a table, but I want when value of avatar is empty to be set with media/profile.png, my model

avatar = models.ImageField(upload_to='media', blank=True, default='media/profile.png')

and return everything in json with JsonResponse(data, safe=False)

[{"id": "1", "avatar": ""}, {"id": "2", "avatar": ""}, {"id": "3", "avatar": "media/profile.png"}, {"id": "4", "avatar": "media/art_xpr.png"}]

and is used in javascript frontend, but the problem is that the avatar is empty in some cases .

Upvotes: 2

Views: 56

Answers (1)

Davit Tovmasyan
Davit Tovmasyan

Reputation: 3588

I believe there is a better way but this also will work

Profile.objects.annotate(
    avatar_or_default=Case(
        When(avatar='', then=Value('media/profile.png')), 
        default=F('avatar'), 
        output_field=CharField()
    )).values('id', 'avatar_or_default')

Output should be something like this

<QuerySet [{'id': 1, 'avatar_or_default': 'media/custom.png'}, {'id': 2, 'avatar_or_default': 'media/profile.png'}, {'id': 3, 'avatar_or_default': 'media/profile.png'}]>

Upvotes: 2

Related Questions