python - Adding a property to a queryset in Django -


i'm creating messaging system , part of want based on whether user sender or receiver of message, different css loads. i'm trying achieve attaching property each message object identifies this.

i have message

#models.py class message(models.model):     def __unicode__(self):         return unicode(self.time_date)      message_from = models.foreignkey(user, related_name="%(class)s_message_from")     message_to = models.foreignkey(user, related_name="%(class)s_message_to")     message = models.textfield()     file = models.filefield(blank=true, null=true)     read = models.booleanfield(default=false)     time_date = models.datetimefield(default=django.utils.timezone.now)     job = models.foreignkey(job, blank=true, null=true) 

and view messages:

def view_messages(request):     messages = message.objects.filter(message_to=request.user, job_id=none).distinct('message_from')     messages_from_user_ids = messages.values_list('message_from', flat=true).distinct()      messages_from_user = user.objects.filter(id__in=messages_from_user_ids)      messages = message.objects.filter(         q(message_to=request.user) & q(message_from_id=messages_from_user_ids[0]) & q(job_id=none) | q(             message_from_id=messages_from_user_ids[0]) & q(             message_from_id=request.user) & q(job_id=none)).order_by('time_date')      messages = message.objects.annotate(foo='true') # error      return render(request, 'freelancestudent/general/messages.html', {'messages': messages,                                                                       'messages_from': messages_from_user}) 

what trying achieve in line commented error test annotations annotating string 'true' every message object, accessible under foo. gives me error 'str' object has no attribute 'resolve_expression'.

what i'm trying achieve, in case i'm going wrong way, check if user sender. idea had of achieving this:

for message in messages:     if message_from == request.user.id:         messages.annotate(sender=true) 

though, isn't right syntax. i'm not sure annotate right function, either. ideas?

if looping through queryset, don't try use annotate, set attribute on instance.

for message in messages:     if message_from == request.user.id:         message.sender = true 

alternatively, think use annotate case:

from django.db.models import booleanfield, case, value, when  messages = message.annotate(     sender=case(         when(message_from=request.user, then=value(true)),         default=value(false),         output_field=booleanfield(),     ) ) 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -