开发者

Limiting Django query results for ajax XML app

Here is my model:

class Members(models.Model):
    firstname         = models.CharField(max_length=30)
    lastname          = models.CharField(max_length=30)
    gender            = models.CharField(max_length=1)
    email             = models.EmailField()
    password          = models.CharField(max_length=30)
    country_code      = models.CharField(max_length=4, choices=COUNTRY_CHOICES)
    zip               = models.CharField(max_length=10)
    will_share        = models.IntegerField()
    will_chat         = models.IntegerField()
    priv_level        = models.IntegerField()
    email_format      = models.CharFiel开发者_如何学编程d(max_length=4, choices=EMAIL_CHOICES)
    created           = models.DateTimeField(auto_now_add=True)
    modified          = models.DateTimeField(auto_now=True)
    last_login        = models.DateTimeField(auto_now=True)
    active            = models.BooleanField()

When I do a query as follows:

Members.objects.all()

How do I limit the fields returned. I only want firstname, lastname and last_login so effectively creating a query like:

SELECT firstname, lastname, last_login FROM members

There are a lot of members and I need to send a lot of XML data to the browser and don't want all the fields returned as it will bulk out the data too much. I have checked all the docs and can't see which option to use.

Is there an easy way for me to turn my limited fields dataset into XML for return to the browser to use in ajax?

Thanks

Rich


  1. QuerySet.values() will let you specify the fields you want, but then the query will no longer return model instances.

  2. Serialization. But of course if you use the previous method then you might not be able to serialize it the same way. Consider using JSON instead.


You can limit the select itself with .only(fields) or .defer(fields) set on your queryset. This will return models that will execute individual selects to populate the missing fields if you access them.

Can't answer the XML serialization part, though.


I found the answer in the end at http://docs.djangoproject.com/en/dev/topics/serialization/

It's possible to limit the fields returned in the actual serialisation!

from django.core import serializers data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜