0

I have this CBV

class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView):
    model = User
    template_name = 'SCHUK/Ansicht.html'
    context_object_name = 'Ansicht'
 


Im using _set to display all users data to staff. But I need to use the data for calculations, how can I convert this to json

  • 1
    Django has a method for converting models to a dictionary. `from django.forms.models import model_to_dict`, then you can use `json.dumps`. You can override the `post()` or `get()` method of your view to implement the logic as you see fit. (Or optionally, `get_context_data` if it needs to be passed into a view.`) – nigel239 Sep 03 '22 at 17:10
  • how would I implement that, just normal def(self) and then instance.__dict__ ? –  Sep 03 '22 at 17:13
  • is it possible to convert it right from the model? with @property it works on Integers –  Sep 03 '22 at 17:21

1 Answers1

0

Use model_to_dict.

Then you can define a method on your model:

from django.forms.models import model_to_dict
class MyModel...
    def get_json(self):
        return json.dumps(model_to_dict(self))
    

In your template, you can just call {{instance.get_json}}.

nigel239
  • 1,485
  • 1
  • 3
  • 23