Accessing a serialized model in javascript

Is it possible to access the attributes of a model that is related to a foreign key class in javascript if the objects is already serialized?

class One(models.Model):
    attr = models.CharField()
    accessMe = models.CharField()

class Two(models.Mode):
   attr = models.ForeinKey(One)

* Function to serialized
def something(request):
   return JsonResponse({'model': model_to_dict(Two.objects.all())})

* How to access in Javascript - JQuery
         complete: function(response){
              var howTo = response.model.attr.accessMe;

On the Jquery Section the variable howTo will have a value of undefined.

The model_to_dict method supplied in Django is a very limited-purpose serialization function. It’s going to return the foreign key value that is actually stored in the FK field.

If you want something to automatically include related fields, then you want to look at a more full-featured serialization package, such as the one included in Django Rest Framework. (I’m sure there are others, none pop into my mind though.)

If you only have two models, I’d recommend doing it manually. I’d only go with the more complex setup under more complex conditions.


1 Like