Use
Python’s standard list-slicing syntax.
———–
e.g.,
>>>Card.objects.order_by(”name”)[0]
First one only
>>>Card.objects.order_by(”name”)[0:2]
The first two objects will be returned
e.g.,
>>>Card.objects.filter(city=”San Diego”).order_by(”-name”)
In model definition,
class Meta:
ordering = ['name']
Use
objects.order_by()
—————-
e.g.,
>>>Card.objects.order_by(”name”)
for reverse order
>>>Card.objects.order_by(”-name”)
filter()
retrieves a QuerySet which is like a list.
To retrieve a single object, use
get()
——————-
e.g.,
>>>Card.objects.get(name=’Hot Pot’)
<Card: Hot Pot>
Use
objects.filter
———
e.g.,
>>>Card.objects.filter(name=’Hot Pot’)
>>>Card.objects.filter(name=’Hot Pot’, city=’San Diego’)
>>>Card.objects.filter(name_contains=’Hot’)
[<Card: Hot Pot>]
Note that here filter() returned a
QuerySet
which is like a list.
__unicode__
is for displaying objects.
———–
For example,
>>>p = Card.objects.create(name=’Hot Pot’, city=’San Diego’)
>>>card_list = Card.objects.all()
>>>card_list
[<Card: Card object>]
without __unicode__, you will see just “Card object”
if you define __unicode__
def __unicode__(self):
return self.name
then, you will see
[<Card: Hot Pot>]
Use the attribute
objects
of models.
Here “objects” is a manager which takes care of all data lookup operation!
To fetch all objects, use
objects.all()
This will return the list of objects.
———
>>>card_list=Card.objects.all()
$ python manage.py syncdb
is for sync of your models to your database.
It looks all of the models in each app in INSTALLED_APPS setting,
checks the database to see whether the appropriate table exist yet or not.
If not, create the tables.
Note that syncdb does not sync changes in models or deletions of models. That is, if you [...]
$ python manage.py sqlall yourappname
prints out all the database tables associated with yourapp.
Note that it is not actually create the tables.
To commit, use
$ python manage.py syncdb
