2013-08-23 53 views
1

我正在重寫應用的後端以使用Django,並且希望儘可能保持前端儘可能不變。我需要與項目之間發送的JSON保持一致。爲Django模型發出特定JSON的清潔器/可重用的方式

models.py我:

class Resource(models.Model): 
    # Name chosen for consistency with old app 
    _id = models.AutoField(primary_key=True) 
    name = models.CharField(max_length=255) 

    @property 
    def bookingPercentage(self): 
     from bookings.models import Booking 
     return Booking.objects.filter(resource=self) 
      .aggregate(models.Sum("percent"))["percent__sum"] 

而且在views.py那得到的JSON所有的資源數據:

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

這個工程完全按照我需要它,但它似乎有點對立的Django和/或Python。使用.all().values將不起作用,因爲bookinPercentage是派生屬性。

另一個問題是,還有其他類似的模型需要以幾乎相同的方式使用JSON表示。我將重寫類似的代碼,併爲模型的值使用不同的名稱。一般來說,有更好的方法來做到這一點,pythonic/djangothonic /不需要手動創建JSON?

回答

-1

這聽起來像你只是想用JSON對你的模型進行序列化。

from django.core import serializers 

data = serializers.serialize('json', Resource.objects.all(), fields=('name','_id', 'bookingPercentage')) 

所以只是通過在模型類,並且要序列化到你的視場:

get_resources(request, model_cls, fields): 

文檔這裏https://docs.djangoproject.com/en/dev/topics/serialization/#id2

+0

在'fields'中包含'_id'和'bookingPercentage'不包含在JSON中,它們仍然包含在一個對象屬性'fields'中,但我需要它們在頂層。 –

+0

爲什麼downvote,只是因爲我的建議不符合你的喜好? – professorDante

+0

這並不是我喜歡的,但它實際上並不適用於我描述的原因。看起來'fields'只能用來限制*條目 –

0

這裏就是你可以在覈心使用串行器我在這種情況下做:

def get_resources(request): 
    resources = list(Resource.objects.all()) 
    for resource in resources: 
     resource.booking = resource.bookingPercentage()      

也就是說,我創建了一個新的屬性f或使用派生屬性的每個實體。它只是一個本地屬性(未存儲在數據庫中),但它可用於您的json.dumps()調用。