开发者

How do I handle database ORM situations like this in Django?

开发者 https://www.devze.com 2023-02-04 05:43 出处:网络
params[\'blog_posts\'] = Content.objects.get(user = blah) params[\'other_vars\'] = \"other stuff\" params[\'votes\'] = 4245
params['blog_posts'] = Content.objects.get(user = blah)
params['other_vars'] = "other stuff"
params['votes'] = 4245

if request.GET.get("format") == "json":
    response = json.dumps(params)
    return HttpResponse(response)
else: 
    return render_to_response("posts.html", params, RequestContext(request))

In my template, I do stuff like this:

{% for p in blog_posts %}
    The author is: {{ p.user.get_profile.about_me }}
{% endfor %}

As you can see, I really utilize the Django's foreign key/database models. 开发者_运维技巧 The problem is...how do I shoot all of these foreign models to JSON?

Even if I serialize blog_posts using django.core.serializers, the JSON won't contain the .user model, and of course won't contain the .get_profile model.


One option is to have your model class itself contain the knowledge of how to serialize itself:

class MyBaseModel(BaseModel):
    def serialize():
        abstract # this will throw an error if it's called without being overwritten

class Post(MyBaseModel):
    title = db.stringProperty()
    body = db.textProperty()
    user = db.referenceProperty(User)

    # etc etc etc
    def serialize(self):
        return {
            'title' : self.title,
            'body' : self.body,
            'user' : self.user.serialize()
            # etc
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号