Prepare Notebook

To run this code, written at the very end of Chapter 3, you need a working empty database.

To move the project into a valid state, please use the command git chapter [chapter-number] to find a valid commit. A commit at the end of Chapter 3, or any commit in Chapters 4-9, should work just fine. Use git checkout [commit] to change the state of the project. Once there, delete the database (if it exists).

$ rm db.sqlite3

To (re-)create the database:

$ ./manage.py migrate

Please see the Read Me file or the actual book for more details.


In [1]:
from datetime import date
from organizer.models import Tag, Startup, NewsLink
from blog.models import Post

Interacting With the Database


In [2]:
edut = Tag(name='Education', slug='education')

In [3]:
edut


Out[3]:
<Tag: Education>

In [4]:
edut.save()

In [5]:
edut.delete()

In [6]:
edut  # still in memory!


Out[6]:
<Tag: Education>

Creation and Destruction with Managers


In [7]:
type(Tag.objects)  # a model manager


Out[7]:
django.db.models.manager.Manager

In [8]:
Tag.objects.create(name='Video Games', slug='video-games')


Out[8]:
<Tag: Video Games>

In [9]:
# create multiple objects in a go!
Tag.objects.bulk_create([
    Tag(name='Django', slug='django'),
    Tag(name='Mobile', slug='mobile'),
    Tag(name='Web', slug='web'),
])


Out[9]:
[<Tag: Django>, <Tag: Mobile>, <Tag: Web>]

In [10]:
Tag.objects.all()


Out[10]:
[<Tag: Django>, <Tag: Mobile>, <Tag: Video Games>, <Tag: Web>]

In [11]:
Tag.objects.all()[0]  # acts like a list


Out[11]:
<Tag: Django>

In [12]:
type(Tag.objects.all())  # is not a list


Out[12]:
django.db.models.query.QuerySet

In [13]:
# managers are not accessible to model instances, only to model classes!
try:
    edut.objects
except AttributeError as e:
    print(e)


Manager isn't accessible via Tag instances

Methods of Data Retrieval


In [14]:
Tag.objects.all()


Out[14]:
[<Tag: Django>, <Tag: Mobile>, <Tag: Video Games>, <Tag: Web>]

In [15]:
Tag.objects.count()


Out[15]:
4

The get method


In [16]:
Tag.objects.get(slug='django')


Out[16]:
<Tag: Django>

In [17]:
type(Tag.objects.all())


Out[17]:
django.db.models.query.QuerySet

In [18]:
type(Tag.objects.get(slug='django'))


Out[18]:
organizer.models.Tag

In [19]:
# case-sensitive!
try:
    Tag.objects.get(slug='Django')
except Tag.DoesNotExist as e:
    print(e)


Tag matching query does not exist.

In [20]:
# the i is for case-Insensitive
Tag.objects.get(slug__iexact='DJANGO')


Out[20]:
<Tag: Django>

In [21]:
Tag.objects.get(slug__istartswith='DJ')


Out[21]:
<Tag: Django>

In [22]:
Tag.objects.get(slug__contains='an')


Out[22]:
<Tag: Django>

In [23]:
# get always returns a single object
try:
    # djangO, mObile, videO-games
    Tag.objects.get(slug__contains='o')
except Tag.MultipleObjectsReturned as e:
    print(e)


get() returned more than one Tag -- it returned 3!

The filter method


In [24]:
## unlike get, can fetch multiple objects
Tag.objects.filter(slug__contains='o')


Out[24]:
[<Tag: Django>, <Tag: Mobile>, <Tag: Video Games>]

In [25]:
type(Tag.objects.filter(slug__contains='o'))


Out[25]:
django.db.models.query.QuerySet

Chaining Calls


In [26]:
Tag.objects.filter(slug__contains='o').order_by('-name')


Out[26]:
[<Tag: Video Games>, <Tag: Mobile>, <Tag: Django>]

In [27]:
# first we call order_by on the manager
Tag.objects.order_by('-name')


Out[27]:
[<Tag: Web>, <Tag: Video Games>, <Tag: Mobile>, <Tag: Django>]

In [28]:
# now we call filter on the manager, and order the resulting queryset
Tag.objects.filter(slug__contains='e').order_by('-name')


Out[28]:
[<Tag: Web>, <Tag: Video Games>, <Tag: Mobile>]

values and values_list


In [29]:
Tag.objects.values_list()


Out[29]:
[(3, 'Django', 'django'), (4, 'Mobile', 'mobile'), (2, 'Video Games', 'video-games'), (5, 'Web', 'web')]

In [30]:
type(Tag.objects.values_list())


Out[30]:
django.db.models.query.ValuesListQuerySet

In [31]:
Tag.objects.values_list('name', 'slug')


Out[31]:
[('Django', 'django'), ('Mobile', 'mobile'), ('Video Games', 'video-games'), ('Web', 'web')]

In [32]:
Tag.objects.values_list('name')


Out[32]:
[('Django',), ('Mobile',), ('Video Games',), ('Web',)]

In [33]:
Tag.objects.values_list('name', flat=True)


Out[33]:
['Django', 'Mobile', 'Video Games', 'Web']

In [34]:
type(Tag.objects.values_list('name', flat=True))


Out[34]:
django.db.models.query.ValuesListQuerySet

Data in Memory vs Data in the Database


In [35]:
jb = Startup.objects.create(
    name='JamBon Software',
    slug='jambon-software',
    contact='django@jambonsw.com',
    description='Web and Mobile Consulting.\n'
                'Django Tutoring.\n',
    founded_date=date(2013, 1, 18),
    website='https://jambonsw.com/',
)
jb  # this output only clear because of __str__()


Out[35]:
<Startup: JamBon Software>

In [36]:
jb.founded_date


Out[36]:
datetime.date(2013, 1, 18)

In [37]:
jb.founded_date = date(2014,1,1)
# we're not calling save() !
jb.founded_date


Out[37]:
datetime.date(2014, 1, 1)

In [38]:
# get version in database
jb = Startup.objects.get(slug='jambon-software')
# work above is all for nought because we didn't save()
jb.founded_date


Out[38]:
datetime.date(2013, 1, 18)

Connecting Data through Relations


In [39]:
djt = Post.objects.create(
    title='Django Training',
    slug='django-training',
    text=(
        "Learn Django in a classroom setting "
        "with JamBon Software."),
)
djt


Out[39]:
<Post: Django Training on 2015-06-09>

In [40]:
djt.pub_date = date(2013, 1, 18)
djt.save()
djt


Out[40]:
<Post: Django Training on 2013-01-18>

In [41]:
type(djt.tags)


Out[41]:
django.db.models.fields.related.create_many_related_manager.<locals>.ManyRelatedManager

In [42]:
type(djt.startups)


Out[42]:
django.db.models.fields.related.create_many_related_manager.<locals>.ManyRelatedManager

In [43]:
djt.tags.all()


Out[43]:
[]

In [44]:
djt.startups.all()


Out[44]:
[]

In [45]:
django = Tag.objects.get(slug__contains='django')
djt.tags.add(django)
djt.tags.all()


Out[45]:
[<Tag: Django>]

In [46]:
django.blog_posts.all()  # a "reverse" relation


Out[46]:
[<Post: Django Training on 2013-01-18>]

In [47]:
django.startup_set.add(jb)  # a "reverse" relation
django.startup_set.all()


Out[47]:
[<Startup: JamBon Software>]

In [48]:
jb.tags.all()  # the "forward" relation


Out[48]:
[<Tag: Django>]

In [49]:
# on more time, for repetition!
djt


Out[49]:
<Post: Django Training on 2013-01-18>

In [50]:
# "forward" relation
djt.startups.add(jb)
djt.startups.all()


Out[50]:
[<Startup: JamBon Software>]

In [51]:
jb.blog_posts.all()  # "reverse" relation


Out[51]:
[<Post: Django Training on 2013-01-18>]