1

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"

  1. 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.

  1. 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.

  1. 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)
Daniel Farrell
  • 9,316
  • 8
  • 39
  • 62
L. P.
  • 165
  • 1
  • 19
  • Do you using `django-restframework`'s serializer [link](https://www.django-rest-framework.org/api-guide/serializers/) – Shakil Feb 20 '19 at 17:52
  • I've never used django-restframework. Not that I'm not open to it. It's just that the .values() my_queryset already has all the fields I need and I was even able to rename the 'foreignModel1__ForeignModel2__title' into title using annotate F. Can DjangoRestFramework be used to serialize a queryset? – L. P. Feb 20 '19 at 17:56
  • Yes, it can. You can safely use it. It will help you do lot of things with minimum afford. – Shakil Feb 20 '19 at 18:02
  • Ok. I'm reading the link you kindly provided and I see something named 'serpy'? I guess I'm trying to find something that can just take the queryset? My concern is the foreign keys and ManytoMany fields. – L. P. Feb 20 '19 at 18:04
  • I would like to suggest to read about `ModelSerializer` and i am going to post a answer how django-rest-framework serializer can solve your problem. – Shakil Feb 20 '19 at 18:10
  • Ok. I greatly appreciate it. Does this mean that I have to convert my app into an API to use rest framework? – L. P. Feb 20 '19 at 18:56
  • No, you don't have to be. you can add `rest-framework` as an additional app in INSTALL_APP and use it like other app. – Shakil Feb 20 '19 at 19:01

1 Answers1

1

Here we have three model TodaysResults, ForeignModel and MModel and I am guessing MModel is a manyTomany relationship with ForeignModel. I am proposing two possible way how we can get all information from TodaysResults serializer.

Possible Solution One

from rest_framework import serializers

class MModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MModel
        fields = ('title',)

class ForeignModelSerializer(serializers.ModelSerializer):
    foreignModel2 = MModelSerializer(many=True) # as it is many to many field
    class Meta:
        model = ForeignModel
        fields = ('name', 'foreignModel2',)

class TodaysResultsSerializer(serializers.ModelSerializer):
    foreignModel1 = ForeignModelSerializer()
    class Meta:
        model = TodaysResults
        fields = ('place', 'foreignModel1')

Now pass your TodaysResults queryset TodaysResultsSerializer and from serializer.data you will get your serialized data.

Possible Solution Two

Even we can do this with one serialize as there is not all fields is required.

class TodaysResultsSerializer(serializers.ModelSerializer):
    class Meta:
        model = TodaysResults
        fields = ('place', 'foreignModel1__name', 'foreignModel1__foreignModel2__title')

Though i am not fully sure but this should also work.

Shakil
  • 4,520
  • 3
  • 26
  • 36
  • you need to pass `TodaysResults.objects.all()`'s queryest for first solution, where you will get your desire fields. and for second one your results should work. – Shakil Feb 20 '19 at 20:37