Django json model with custom fields view

I have the following model:

class Messages(models.Model):
    userid = models.ForeignKey(User)
    time = models.TimeField(default=datetime.datetime.now)
    content = models.CharField(max_length=255)
    id = models.AutoField(primary_key=True)

      

I want to use this model with custom view to pass it to javascript. I used the following code for this, iterating through the QuerySet

messages = Messages.objects.all()
passed_messages = []
for singleMess in messages:
    passed_messages.append(get_message(singleMess))
response = json.dumps(passed_messages)

def get_message(message):
    return {
        'user': User.objects.get_by_natural_key(message.userid).username,
        'content': message.content,
        'hour': message.time.hour,
        'minute': message.time.minute,
        'id': message.id
    }

      

But this part looks ugly. Is there a way to replace it with something nicer. I could use the following

__repr__ in models.py 
django.core.serializers 
django.forms.models.model_to_dict 
Messages.objects.all().values()

      

I just don't know how to find it. for example

  • json.dumps needs a clean list of Python dictionaries, but __ repr __ returns a QuerySet , which I don't know how to pass.
  • If I use model_to_dict or serializers or list (messages.values ​​()) , I cannot join the username of the user field instead of User ID.
+3


source to share


1 answer


I added a property to the model class

class Messages(models.Model):
    userid = models.ForeignKey(User)
    time = models.TimeField(default=datetime.datetime.now)
    content = models.CharField(max_length=255)
    id = models.AutoField(primary_key=True)

  @property
  def json(self):
    return {
    'user': User.objects.get_by_natural_key(self.userid).username,
    'content': self.content,
    'time': self.time.strftime("%H:%M:%S"),
    'id': self.id
    }

      



And the used understanding:

import json
messages = Messages.objects.all()
json.dumps([message.json for message in messages])

      

+2


source







All Articles