python - Cleaner / reusable way to emit specific JSON for django models -


i'm rewriting end of app use django, , i'd keep front end untouched possible. need consistent json sent between projects.

in models.py have:

class resource(models.model):     # name chosen consistency old app     _id = models.autofield(primary_key=true)     name = models.charfield(max_length=255)      @property     def bookingpercentage(self):         bookings.models import booking         return booking.objects.filter(resource=self)             .aggregate(models.sum("percent"))["percent__sum"] 

and in views.py gets resource data json:

def get_resources(request):     resources = []     resource in resource.objects.all():         resources.append({             "_id": resource._id,             "name": resource.first,             "bookingpercentage": resource.bookingpercentage                              })     return httpresponse(json.dumps(resources)) 

this works need to, seems antithetical django and/or python. using .all().values not work because bookinpercentage derived property.

another issue there other similar models need json representations in pretty same way. rewriting similar code , using different names values of models. in general there better way more pythonic/djangothonic/does not require manual creation of json?

here's in situation:

def get_resources(request):     resources = list(resource.objects.all())     resource in resources:         resource.booking = resource.bookingpercentage()                     

that is, create new attribute each entity using derived property. it's local attribute (not stored in database), it's available json.dumps() call.


Comments

Popular posts from this blog

Line ending issue with Mercurial or Visual Studio -

java - Jtable duplicate Rows -

java - Run a .jar on Heroku -