I'm trying to pass JSON objects to my template. I have some complicated relationships that I can't modify. Based on OS posts I've tried different things. The ones that I think brought me close are:
I created a .values() queryset that looks like this
def my_queryset():
results=TodaysResults.objects.values('id','foreignModel1__name',
'foreignModel1__ForeignModel2__title')
print (myquery_set)
my_queryset gives me all the values I need. So I tried to convert it using the methods below. 1)
def make_querydict():
results=TodaysResults.objects.values('id','foreignModel1__name',
'foreignModel1__ForeignModel2__title')
json_results=json.dumps(list(results,cls=DjangoJSONEncoder))
print (json_results)
I get the following error:
"TypeError: list() takes no keyword arguments"
I tried this as well:
def serialize(): fields = ['id','foreignModel1__name','foreignModel1__ForeignModel2__title'] qs = TodaysResults.objects.all() json_data = serializers.serialize('json',qs,fields=fields) print(json_data)
But when I print the json_data in only shows id and not the foreign values.
Based on a few answers like this(from 2012) that were along the same lines And I tried:
def for_JSON_response(): response=JsonResponse(dict(results_info=list(TodaysResultslts.objects.values('id','foreignModel1__name', 'foreignModel1__ForeignModel2__title') print(response)
I don't get any errors but it does not print anything.So, I'm assuming nothing happened.
Based on this I tried:
def my_queryset(): results=TodaysResults.objects.values('id','foreignModel1__name', 'foreignModel1__ForeignModel2__title') print (JsonResponse(results, safe=False)) I get:
TypeError: Object of type QuerySet is not JSON serializable
And I tried:
def my_queryset():
results=TodaysResults.objects.values('id','foreignModel1__name',
'foreignModel1__ForeignModel2__title')
results_json = serializers.serialize('json',results)
And I got:
AttributeError: 'dict' object has no attribute '_meta'
I've been looking around a lot and some of the responses look outdated. My attempts above are the ones that I believe came the closest to converting the valuesqueryset to json or getting the values I need into JSON. Is there a way of making a chained query like the one I have in my_queryset and convert it to JSON?
Models.Py Simplified for this example
class TodaysResults(models.Model):
place = models.CharField(max_length=255)
ForeignModel1 = models.ForeignKey(ForeignModel,related_name='m1')
class ForeignModel(models.Model):
name = Models.CharField(max_length=255)
ForeignModel2 = models.ManyToManyField(M2M, related_name='m2')
class M2M(models.Model):
title = Models.CharField(max_length=255)