I am beginning to learn Python and Django. I want to know how if I have a simple class of “player” with some properties, like: name, points, inventory, how would I make the class also write the values to the database if they are changed. My thinking is that I create Django data models and then call the .save method within my classes. Is this correct?
I am beginning to learn Python and Django. I want to know how if
Share
You are correct that you call the
save()method to save models to your db, But you don’t have to define thesavemethod within your model classes if you don’t want to. It would be extremely helpful to go through the django tutorial which explains all.https://docs.djangoproject.com/en/dev/intro/tutorial01/
https://docs.djangoproject.com/en/dev/topics/db/models/
Explains django models
django uses its own ORM (object-relational mapping)
This does exacxtly what it sounds like maps your django/python objects (models) to your backend.
It provides a sleek, intuitive, pythonic, very easy to use interface for creating models (tables in your rdbms) adding data and retrieving data.
First you would define your model
django provides commands for chanign this python object into a table.
python manage.py syncdbyou could also use
python manage.py sql <appname>to show the actual sql that django is generating to turn this object into a table.Once you have a storage for this object you can create new ones in the same manner you would create python objects
Calling
save()actually writes the object to your backend.