Issue the following command to create a table for the Link data model in the database:
$ python manage.py syncdb
You can examine the SQL query generated by Django by running the following command:
$ python manage.py sql bookmarks
The power of Django's Python database API does not stop at creating tables. We can use it to create entries in the table, to modify entries, to search and browse the table contents, among many other things. To explore the API, we will use the Python interactive console. To launch the console use this command:
$ python manage.py shell
Now import the contents of the models module:
>>> from bookmarks.models import *
To add a new link, create a new instance of the Link class and call the save method on it:
>>> link1 = Link(url='http://www.packtpub.com/')
>>> link1.save()
Table fields become attributes of objects. To examine and change a link's URL, type the following:
>>> link2.url
'http://www.example.com/'
>>> link2.url = 'http://www.google.com/'
>>> link2.save()
To get a list of all available Link objects, type the following:
>>> links = Link.objects.all()
>>> for link in links:
To get an object by ID, type the following:
>>> Link.objects.get(id=1)
<Link: Link object>
Finally, to delete a link, use the following:
>>> link2.delete()
>>> Link.objects.count()
management of user accounts is so common that Django comes with a user model ready for us to use. This model contains fields that are often associated with user accounts, such as username, password and email and so on. The model is called User and it's located in the django.contrib.auth.models package.
To explore the contents of this model, open the interactive console and type
the following:
>>> from django.contrib.auth.models import User
>>> User.objects.all()
[<User: ayman>]
You can examine the fields of User objects by using the dir function:
>>> user = User.objects.get(id=1)
>>> dir(user)