Django ORM access User table through multiple models -
views.py
i'm creating queryset want serialize , return json. queryset looks this:
all_objects = program.objects.all() test_data = serializers.serialize("json", all_objects, use_natural_keys=true)
this pulls except 'user' model (which linked across 2 models).
models.py
from django.db import models django.contrib.auth.models import user class time(models.model): user = models.foreignkey(user) ... class costcode(models.model): program_name = models.textfield() ... class program(models.model): time = models.foreignkey(time) program_select = models.foreignkey(costcode) ...
question
my returned data has time, program, , costcode information, i'm unable query 'user' table. how can 'username' (from user table) in same queryset?
note: i've changed queryset all_objects = time.objects.all()
, gets user info, doesn't pull in 'costcode'. models have modelmanagers return get_by_natural_key
relevant fields appear in json.
ultimately, want data 4 models appear in serialized json fields, i'm missing 'username'.
here's picture of how json object appears in firebug:
thanks help!
it seems bit heavyweight @ first glance @ using django rest framework:
http://www.django-rest-framework.org/api-guide/serializers#modelserializer
you can define , use serializer classes without having else framework. serializer returns python dict can dumped json.
to fields each related model nested dicts do:
class programserializer(serializers.modelserializer): class meta: model = program depth = 2 all_objects = program.objects.all() serializer = programserializer(all_objects, many=true) json_str = json.dumps(serializer.data)
to customise fields included each model need define modelserializer class each of models, example output username
time.user
:
class userserializer(serializers.modelserializer): class meta: model = user fields = ('username', ) class timeserializer(serializers.modelserializer): """ specifying field here rather relying on `depth` automatically render nested relations allows specify custom serializer class """ user = userserializer() class meta: model = time class programserializer(serializers.modelserializer): time = timeserializer() class meta: model = program depth = 1 # render nested costcode default output all_objects = program.objects.all() serializer = programserializer(all_objects, many=true) json_str = json.dumps(serializer.data)
Comments
Post a Comment