Django

Code

Show
Ignore:
Timestamp:
04/26/08 21:50:16 (9 months ago)
Author:
mtredinnick
Message:

Merged the queryset-refactor branch into trunk.

This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.

Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/tests/modeltests/basic/models.py

    r7132 r7477  
    293293[<Article: Default headline>] 
    294294 
    295 # Note that you can't use 'offset' without 'limit' (on some dbs), so this doesn't work: 
    296 >>> Article.objects.all()[2:] 
    297 Traceback (most recent call last): 
    298     ... 
    299 AssertionError: 'offset' is not allowed without 'limit' 
     295# Using an offset without a limit is also possible. 
     296>>> Article.objects.all()[5:] 
     297[<Article: Fourth article>, <Article: Article 7>, <Article: Updated article 8>] 
    300298 
    301299# Also, once you have sliced you can't filter, re-order or combine 
  • django/trunk/tests/modeltests/custom_columns/models.py

    r5876 r7477  
    5656>>> art.authors = [a, a2] 
    5757 
    58 # Although the table and column names on Author have been set to  
    59 # custom values, nothing about using the Author model has changed... 
     58# Although the table and column names on Author have been set to custom values, 
     59# nothing about using the Author model has changed... 
    6060 
    6161# Query the available authors 
     
    7272Traceback (most recent call last): 
    7373    ... 
    74 TypeError: Cannot resolve keyword 'firstname' into field. Choices are: article, id, first_name, last_name 
     74FieldError: Cannot resolve keyword 'firstname' into field. Choices are: article, first_name, id, last_name 
    7575 
    7676>>> a = Author.objects.get(last_name__exact='Smith') 
  • django/trunk/tests/modeltests/field_subclassing/models.py

    r7294 r7477  
    66from django.utils.encoding import force_unicode 
    77from django.core import serializers 
     8from django.core.exceptions import FieldError 
    89 
    910class Small(object): 
     
    5152        if lookup_type == 'isnull': 
    5253            return [] 
    53         raise TypeError('Invalid lookup type: %r' % lookup_type) 
     54        raise FieldError('Invalid lookup type: %r' % lookup_type) 
    5455 
    5556    def flatten_data(self, follow, obj=None): 
     
    9596Traceback (most recent call last): 
    9697... 
    97 TypeError: Invalid lookup type: 'lt' 
     98FieldError: Invalid lookup type: 'lt' 
    9899 
    99100# Serialization works, too. 
  • django/trunk/tests/modeltests/lookup/models.py

    r7322 r7477  
    163163Traceback (most recent call last): 
    164164    ... 
    165 FieldDoesNotExist: Article has no field named 'id_plus_two' 
     165FieldError: Cannot resolve keyword 'id_plus_two' into field. Choices are: headline, id, id_plus_one, pub_date 
    166166 
    167167# If you don't specify field names to values(), all are returned. 
    168168>>> list(Article.objects.filter(id=5).values()) == [{'id': 5, 'headline': 'Article 5', 'pub_date': datetime(2005, 8, 1, 9, 0)}] 
    169169True 
     170 
     171# values_list() is similar to values(), except that the results are returned as 
     172# a list of tuples, rather than a list of dictionaries. Within each tuple, the 
     173# order of the elemnts is the same as the order of fields in the values_list() 
     174# call. 
     175>>> Article.objects.values_list('headline') 
     176[(u'Article 5',), (u'Article 6',), (u'Article 4',), (u'Article 2',), (u'Article 3',), (u'Article 7',), (u'Article 1',)] 
     177 
     178>>> Article.objects.values_list('id').order_by('id') 
     179[(1,), (2,), (3,), (4,), (5,), (6,), (7,)] 
     180>>> Article.objects.values_list('id', flat=True).order_by('id') 
     181[1, 2, 3, 4, 5, 6, 7] 
     182 
     183>>> Article.objects.extra(select={'id_plus_one': 'id+1'}).order_by('id').values_list('id') 
     184[(1,), (2,), (3,), (4,), (5,), (6,), (7,)] 
     185>>> Article.objects.extra(select={'id_plus_one': 'id+1'}).order_by('id').values_list('id_plus_one', 'id') 
     186[(2, 1), (3, 2), (4, 3), (5, 4), (6, 5), (7, 6), (8, 7)] 
     187>>> Article.objects.extra(select={'id_plus_one': 'id+1'}).order_by('id').values_list('id', 'id_plus_one') 
     188[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8)] 
     189 
     190>>> Article.objects.values_list('id', 'headline', flat=True) 
     191Traceback (most recent call last): 
     192... 
     193TypeError: 'flat' is not valid when values_list is called with more than one field. 
    170194 
    171195# Every DateField and DateTimeField creates get_next_by_FOO() and 
     
    241265>>> Article.objects.none().filter(headline__startswith='Article') 
    242266[] 
     267>>> Article.objects.filter(headline__startswith='Article').none() 
     268[] 
    243269>>> Article.objects.none().count() 
    2442700 
     
    257283Traceback (most recent call last): 
    258284    ... 
    259 TypeError: Cannot resolve keyword 'pub_date_year' into field. Choices are: id, headline, pub_date 
     285FieldError: Cannot resolve keyword 'pub_date_year' into field. Choices are: headline, id, pub_date 
    260286 
    261287>>> Article.objects.filter(headline__starts='Article') 
    262288Traceback (most recent call last): 
    263289    ... 
    264 TypeError: Cannot resolve keyword 'headline__starts' into field. Choices are: id, headline, pub_date 
     290FieldError: Join on field 'headline' not permitted. 
    265291 
    266292# Create some articles with a bit more interesting headlines for testing field lookups: 
  • django/trunk/tests/modeltests/many_to_many/models.py

    r5876 r7477  
    127127[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>] 
    128128 
     129# Excluding a related item works as you would expect, too (although the SQL 
     130# involved is a little complex). 
     131>>> Article.objects.exclude(publications=p2) 
     132[<Article: Django lets you build Web apps easily>] 
     133 
    129134# If we delete a Publication, its Articles won't be able to access it. 
    130135>>> p1.delete() 
  • django/trunk/tests/modeltests/many_to_one/models.py

    r5876 r7477  
    146146 
    147147# The underlying query only makes one join when a related table is referenced twice. 
    148 >>> query = Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith') 
    149 >>> null, sql, null = query._get_sql_clause() 
     148>>> queryset = Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith') 
     149>>> sql = queryset.query.as_sql()[0] 
    150150>>> sql.count('INNER JOIN') 
    1511511 
    152152 
    153153# The automatically joined table has a predictable name. 
    154 >>> Article.objects.filter(reporter__first_name__exact='John').extra(where=["many_to_one_article__reporter.last_name='Smith'"]) 
     154>>> Article.objects.filter(reporter__first_name__exact='John').extra(where=["many_to_one_reporter.last_name='Smith'"]) 
    155155[<Article: John's second story>, <Article: This is a test>] 
    156156 
    157157# And should work fine with the unicode that comes out of 
    158158# newforms.Form.cleaned_data 
    159 >>> Article.objects.filter(reporter__first_name__exact='John').extra(where=["many_to_one_article__reporter.last_name='%s'" % u'Smith']) 
     159>>> Article.objects.filter(reporter__first_name__exact='John').extra(where=["many_to_one_reporter.last_name='%s'" % u'Smith']) 
    160160[<Article: John's second story>, <Article: This is a test>] 
    161161 
     
    180180Traceback (most recent call last): 
    181181    ... 
    182 TypeError: Cannot resolve keyword 'reporter_id' into field. Choices are: id, headline, pub_date, reporter 
     182FieldError: Cannot resolve keyword 'reporter_id' into field. Choices are: headline, id, pub_date, reporter 
    183183 
    184184# You need to specify a comparison clause 
     
    186186Traceback (most recent call last): 
    187187    ... 
    188 TypeError: Cannot resolve keyword 'reporter_id' into field. Choices are: id, headline, pub_date, reporter 
     188FieldError: Cannot resolve keyword 'reporter_id' into field. Choices are: headline, id, pub_date, reporter 
    189189 
    190190# You can also instantiate an Article by passing 
     
    250250>>> Reporter.objects.filter(article__reporter=r).distinct() 
    251251[<Reporter: John Smith>] 
     252 
     253# It's possible to use values() calls across many-to-one relations. (Note, too, that we clear the ordering here so as not to drag the 'headline' field into the columns being used to determine uniqueness.) 
     254>>> d = {'reporter__first_name': u'John', 'reporter__last_name': u'Smith'} 
     255>>> list(Article.objects.filter(reporter=r).distinct().order_by().values('reporter__first_name', 'reporter__last_name')) == [d] 
     256True 
    252257 
    253258# If you delete a reporter, his articles will be deleted. 
  • django/trunk/tests/modeltests/many_to_one_null/models.py

    r5876 r7477  
    8181[<Article: Third>] 
    8282 
     83# We can achieve the same thing by filtering for the case where the reporter is 
     84# None. 
     85>>> Article.objects.filter(reporter=None) 
     86[<Article: Third>] 
     87 
    8388# Set the reporter for the Third article 
    8489>>> r.article_set.add(a3) 
  • django/trunk/tests/modeltests/model_inheritance/models.py

    r5876 r7477  
    22XX. Model inheritance 
    33 
    4 Model inheritance isn't yet supported. 
     4Model inheritance exists in two varieties: 
     5    - abstract base classes which are a way of specifying common 
     6      information inherited by the subclasses. They don't exist as a separate 
     7      model. 
     8    - non-abstract base classes (the default), which are models in their own 
     9      right with their own database tables and everything. Their subclasses 
     10      have references back to them, created automatically. 
     11 
     12Both styles are demonstrated here. 
    513""" 
    614 
    715from django.db import models 
     16 
     17# 
     18# Abstract base classes 
     19# 
     20 
     21class CommonInfo(models.Model): 
     22    name = models.CharField(max_length=50) 
     23    age = models.PositiveIntegerField() 
     24 
     25    class Meta: 
     26        abstract = True 
     27        ordering = ['name'] 
     28 
     29    def __unicode__(self): 
     30        return u'%s %s' % (self.__class__.__name__, self.name) 
     31 
     32class Worker(CommonInfo): 
     33    job = models.CharField(max_length=50) 
     34 
     35class Student(CommonInfo): 
     36    school_class = models.CharField(max_length=10) 
     37 
     38    class Meta: 
     39        pass 
     40 
     41# 
     42# Multi-table inheritance 
     43# 
     44 
     45class Chef(models.Model): 
     46    name = models.CharField(max_length=50) 
     47 
     48    def __unicode__(self): 
     49        return u"%s the chef" % self.name 
    850 
    951class Place(models.Model): 
     
    1456        return u"%s the place" % self.name 
    1557 
    16 class Restaurant(Place): 
     58class Rating(models.Model): 
     59    rating = models.IntegerField(null=True, blank=True) 
     60 
     61    class Meta: 
     62        abstract = True 
     63        ordering = ['-rating'] 
     64 
     65class Restaurant(Place, Rating): 
    1766    serves_hot_dogs = models.BooleanField() 
    1867    serves_pizza = models.BooleanField() 
     68    chef = models.ForeignKey(Chef, null=True, blank=True) 
     69 
     70    class Meta(Rating.Meta): 
     71        db_table = 'my_restaurant' 
    1972 
    2073    def __unicode__(self): 
     
    2780        return u"%s the italian restaurant" % self.name 
    2881 
     82class Supplier(Place): 
     83    customers = models.ManyToManyField(Restaurant, related_name='provider') 
     84 
     85    def __unicode__(self): 
     86        return u"%s the supplier" % self.name 
     87 
     88class ParkingLot(Place): 
     89    # An explicit link to the parent (we can control the attribute name). 
     90    parent = models.OneToOneField(Place, primary_key=True, parent_link=True) 
     91    main_site = models.ForeignKey(Place, related_name='lot') 
     92 
     93    def __unicode__(self): 
     94        return u"%s the parking lot" % self.name 
     95 
    2996__test__ = {'API_TESTS':""" 
    30 # Make sure Restaurant has the right fields in the right order. 
    31 >>> [f.name for f in Restaurant._meta.fields] 
    32 ['id', 'name', 'address', 'serves_hot_dogs', 'serves_pizza'] 
    33  
    34 # Make sure ItalianRestaurant has the right fields in the right order. 
    35 >>> [f.name for f in ItalianRestaurant._meta.fields] 
    36 ['id', 'name', 'address', 'serves_hot_dogs', 'serves_pizza', 'serves_gnocchi'] 
     97# The Student and Worker models both have 'name' and 'age' fields on them and 
     98# inherit the __unicode__() method, just as with normal Python subclassing. 
     99# This is useful if you want to factor out common information for programming 
     100# purposes, but still completely independent separate models at the database 
     101# level. 
     102 
     103>>> w = Worker(name='Fred', age=35, job='Quarry worker') 
     104>>> w.save() 
     105>>> w2 = Worker(name='Barney', age=34, job='Quarry worker') 
     106>>> w2.save() 
     107>>> s = Student(name='Pebbles', age=5, school_class='1B') 
     108>>> s.save() 
     109>>> unicode(w) 
     110u'Worker Fred' 
     111>>> unicode(s) 
     112u'Student Pebbles' 
     113 
     114# The children inherit the Meta class of their parents (if they don't specify 
     115# their own). 
     116>>> Worker.objects.values('name') 
     117[{'name': u'Barney'}, {'name': u'Fred'}] 
     118 
     119# Since Student does not subclass CommonInfo's Meta, it has the effect of 
     120# completely overriding it. So ordering by name doesn't take place for Students. 
     121>>> Student._meta.ordering 
     122[] 
     123 
     124# However, the CommonInfo class cannot be used as a normal model (it doesn't 
     125# exist as a model). 
     126>>> CommonInfo.objects.all() 
     127Traceback (most recent call last): 
     128    ... 
     129AttributeError: type object 'CommonInfo' has no attribute 'objects' 
     130 
     131# The Place/Restaurant/ItalianRestaurant models, on the other hand, all exist 
     132# as independent models. However, the subclasses also have transparent access 
     133# to the fields of their ancestors. 
    37134 
    38135# Create a couple of Places. 
     
    42139>>> p2.save() 
    43140 
    44 # Test constructor for Restaurant. 
    45 >>> r = Restaurant(name='Demon Dogs', address='944 W. Fullerton', serves_hot_dogs=True, serves_pizza=False
     141Test constructor for Restaurant. 
     142>>> r = Restaurant(name='Demon Dogs', address='944 W. Fullerton',serves_hot_dogs=True, serves_pizza=False, rating=2
    46143>>> r.save() 
    47144 
    48145# Test the constructor for ItalianRestaurant. 
    49 >>> ir = ItalianRestaurant(name='Ristorante Miron', address='1234 W. Elm', serves_hot_dogs=False, serves_pizza=False, serves_gnocchi=True) 
     146>>> c = Chef(name="Albert") 
     147>>> c.save() 
     148>>> ir = ItalianRestaurant(name='Ristorante Miron', address='1234 W. Ash', serves_hot_dogs=False, serves_pizza=False, serves_gnocchi=True, rating=4, chef=c) 
    50149>>> ir.save() 
    51  
     150>>> ir.address = '1234 W. Elm' 
     151>>> ir.save() 
     152 
     153# Make sure Restaurant and ItalianRestaurant have the right fields in the right 
     154# order. 
     155>>> [f.name for f in Restaurant._meta.fields] 
     156['id', 'name', 'address', 'place_ptr', 'rating', 'serves_hot_dogs', 'serves_pizza', 'chef'] 
     157>>> [f.name for f in ItalianRestaurant._meta.fields] 
     158['id', 'name', 'address', 'place_ptr', 'rating', 'serves_hot_dogs', 'serves_pizza', 'chef', 'restaurant_ptr', 'serves_gnocchi'] 
     159>>> Restaurant._meta.ordering 
     160['-rating'] 
     161 
     162# Even though p.supplier for a Place 'p' (a parent of a Supplier), a Restaurant 
     163# object cannot access that reverse relation, since it's not part of the 
     164# Place-Supplier Hierarchy. 
     165>>> Place.objects.filter(supplier__name='foo') 
     166[] 
     167>>> Restaurant.objects.filter(supplier__name='foo') 
     168Traceback (most recent call last): 
     169    ... 
     170FieldError: Cannot resolve keyword 'supplier' into field. Choices are: address, chef, id, italianrestaurant, lot, name, place_ptr, provider, rating, serves_hot_dogs, serves_pizza 
     171 
     172# Parent fields can be used directly in filters on the child model. 
     173>>> Restaurant.objects.filter(name='Demon Dogs') 
     174[<Restaurant: Demon Dogs the restaurant>] 
     175>>> ItalianRestaurant.objects.filter(address='1234 W. Elm') 
     176[<ItalianRestaurant: Ristorante Miron the italian restaurant>] 
     177 
     178# Filters against the parent model return objects of the parent's type. 
     179>>> Place.objects.filter(name='Demon Dogs') 
     180[<Place: Demon Dogs the place>] 
     181 
     182# Since the parent and child are linked by an automatically created 
     183# OneToOneField, you can get from the parent to the child by using the child's 
     184# name. 
     185>>> place = Place.objects.get(name='Demon Dogs') 
     186>>> place.restaurant 
     187<Restaurant: Demon Dogs the restaurant> 
     188 
     189>>> Place.objects.get(name='Ristorante Miron').restaurant.italianrestaurant 
     190<ItalianRestaurant: Ristorante Miron the italian restaurant> 
     191>>> Restaurant.objects.get(name='Ristorante Miron').italianrestaurant 
     192<ItalianRestaurant: Ristorante Miron the italian restaurant> 
     193 
     194# This won't work because the Demon Dogs restaurant is not an Italian 
     195# restaurant. 
     196>>> place.restaurant.italianrestaurant 
     197Traceback (most recent call last): 
     198    ... 
     199DoesNotExist: ItalianRestaurant matching query does not exist. 
     200 
     201# Related objects work just as they normally do. 
     202 
     203>>> s1 = Supplier(name="Joe's Chickens", address='123 Sesame St') 
     204>>> s1.save() 
     205>>> s1.customers = [r, ir] 
     206>>> s2 = Supplier(name="Luigi's Pasta", address='456 Sesame St') 
     207>>> s2.save() 
     208>>> s2.customers = [ir] 
     209 
     210# This won't work because the Place we select is not a Restaurant (it's a 
     211# Supplier). 
     212>>> p = Place.objects.get(name="Joe's Chickens") 
     213>>> p.restaurant 
     214Traceback (most recent call last): 
     215    ... 
     216DoesNotExist: Restaurant matching query does not exist. 
     217 
     218# But we can descend from p to the Supplier child, as expected. 
     219>>> p.supplier 
     220<Supplier: Joe's Chickens the supplier> 
     221 
     222>>> ir.provider.order_by('-name') 
     223[<Supplier: Luigi's Pasta the supplier>, <Supplier: Joe's Chickens the supplier>] 
     224 
     225>>> Restaurant.objects.filter(provider__name__contains="Chickens") 
     226[<Restaurant: Ristorante Miron the restaurant>, <Restaurant: Demon Dogs the restaurant>] 
     227>>> ItalianRestaurant.objects.filter(provider__name__contains="Chickens") 
     228[<ItalianRestaurant: Ristorante Miron the italian restaurant>] 
     229 
     230>>> park1 = ParkingLot(name='Main St', address='111 Main St', main_site=s1) 
     231>>> park1.save() 
     232>>> park2 = ParkingLot(name='Well Lit', address='124 Sesame St', main_site=ir) 
     233>>> park2.save() 
     234 
     235>>> Restaurant.objects.get(lot__name='Well Lit') 
     236<Restaurant: Ristorante Miron the restaurant> 
     237 
     238# The update() command can update fields in parent and child classes at once 
     239# (although it executed multiple SQL queries to do so). 
     240>>> Restaurant.objects.filter(serves_hot_dogs=True, name__contains='D').update(name='Demon Puppies', serves_hot_dogs=False) 
     241>>> r1 = Restaurant.objects.get(pk=r.pk) 
     242>>> r1.serves_hot_dogs == False 
     243True 
     244>>> r1.name 
     245u'Demon Puppies' 
     246 
     247# The values() command also works on fields from parent models. 
     248>>> d = {'rating': 4, 'name': u'Ristorante Miron'} 
     249>>> list(ItalianRestaurant.objects.values('name', 'rating')) == [d] 
     250True 
     251 
     252# select_related works with fields from the parent object as if they were a 
     253# normal part of the model. 
     254>>> from django import db 
     255>>> from django.conf import settings 
     256>>> settings.DEBUG = True 
     257>>> db.reset_queries() 
     258>>> ItalianRestaurant.objects.all()[0].chef 
     259<Chef: Albert the chef> 
     260>>> len(db.connection.queries) 
     261
     262>>> ItalianRestaurant.objects.select_related('chef')[0].chef 
     263<Chef: Albert the chef> 
     264>>> len(db.connection.queries) 
     265
     266>>> settings.DEBUG = False 
    52267 
    53268"""} 
  • django/trunk/tests/modeltests/one_to_one/models.py

    r5876 r7477  
    77""" 
    88 
    9 from django.db import models 
     9from django.db import models, connection 
    1010 
    1111class Place(models.Model): 
     
    1717 
    1818class Restaurant(models.Model): 
    19     place = models.OneToOneField(Place
     19    place = models.OneToOneField(Place, primary_key=True
    2020    serves_hot_dogs = models.BooleanField() 
    2121    serves_pizza = models.BooleanField() 
     
    3838    link = models.OneToOneField(ManualPrimaryKey) 
    3939    name = models.CharField(max_length = 50) 
     40 
     41class MultiModel(models.Model): 
     42    link1 = models.OneToOneField(Place) 
     43    link2 = models.OneToOneField(ManualPrimaryKey) 
     44    name = models.CharField(max_length=50) 
     45 
     46    def __unicode__(self): 
     47        return u"Multimodel %s" % self.name 
    4048 
    4149__test__ = {'API_TESTS':""" 
     
    6472DoesNotExist: Restaurant matching query does not exist. 
    6573 
    66 # Set the place using assignment notation. Because place is the primary key on Restaurant, 
    67 # the save will create a new restaurant 
     74# Set the place using assignment notation. Because place is the primary key on 
     75# Restaurant, the save will create a new restaurant 
    6876>>> r.place = p2 
    6977>>> r.save() 
     
    7381<Place: Ace Hardware the place> 
    7482 
    75 # Set the place back again, using assignment in the reverse direction 
    76 # Need to reget restaurant object first, because the reverse set 
    77 # can't update the existing restaurant instance 
     83# Set the place back again, using assignment in the reverse direction. Need to 
     84# reload restaurant object first, because the reverse set can't update the 
     85# existing restaurant instance 
    7886>>> p1.restaurant = r 
    7987>>> r.save() 
     
    8795# Restaurant.objects.all() just returns the Restaurants, not the Places. 
    8896# Note that there are two restaurants - Ace Hardware the Restaurant was created 
    89 # in the call to r.place = p2. This means there are multiple restaurants referencing 
    90 # a single place... 
     97# in the call to r.place = p2. 
    9198>>> Restaurant.objects.all() 
    9299[<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>] 
     
    166173>>> o2 = RelatedModel(link=o1, name="secondary") 
    167174>>> o2.save() 
     175 
     176# You can have multiple one-to-one fields on a model, too. 
     177>>> x1 = MultiModel(link1=p1, link2=o1, name="x1") 
     178>>> x1.save() 
     179>>> o1.multimodel 
     180<MultiModel: Multimodel x1> 
     181 
     182# This will fail because each one-to-one field must be unique (and link2=o1 was 
     183# used for x1, above). 
     184>>> MultiModel(link1=p2, link2=o1, name="x1").save() 
     185Traceback (most recent call last): 
     186    ... 
     187IntegrityError: ... 
     188 
     189# Because the unittests all use a single connection, we need to force a 
     190# reconnect here to ensure the connection is clean (after the previous 
     191# IntegrityError). 
     192>>> connection.close() 
    168193"""} 
  • django/trunk/tests/modeltests/ordering/models.py

    r7119 r7477  
    4949[<Article: Article 1>, <Article: Article 3>, <Article: Article 2>, <Article: Article 4>] 
    5050 
     51# Only the last order_by has any effect (since they each override any previous 
     52# ordering). 
     53>>> Article.objects.order_by('id') 
     54[<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>] 
     55>>> Article.objects.order_by('id').order_by('-headline') 
     56[<Article: Article 4>, <Article: Article 3>, <Article: Article 2>, <Article: Article 1>] 
     57 
    5158# Use the 'stop' part of slicing notation to limit the results. 
    5259>>> Article.objects.order_by('headline')[:2] 
     
    6572>>> Article.objects.order_by('?') 
    6673[...] 
     74 
     75# Ordering can be reversed using the reverse() method on a queryset. This 
     76# allows you to extract things like "the last two items" (reverse and then 
     77# take the first two). 
     78>>> Article.objects.all().reverse()[:2] 
     79[<Article: Article 1>, <Article: Article 3>] 
    6780"""} 
  • django/trunk/tests/modeltests/or_lookups/models.py

    r7379 r7477  
    55combine QuerySet objects using & and | operators. 
    66 
    7 Alternatively, use positional arguments, and pass one or more expressions 
    8 of clauses using the variable ``django.db.models.Q`` (or any object with 
    9 a get_sql method). 
    10  
    11  
     7Alternatively, use positional arguments, and pass one or more expressions of 
     8clauses using the variable ``django.db.models.Q`` (or any object with an 
     9add_to_query method). 
    1210""" 
    1311 
     
    7371>>> Article.objects.filter(pk__in=[1,2,3]) 
    7472[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>] 
     73>>> Article.objects.filter(pk__in=(1,2,3)) 
     74[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>] 
    7575 
    7676>>> Article.objects.filter(pk__in=[1,2,3,4]) 
     
    9292>>> Article.objects.filter(Q(headline__contains='bye'), headline__startswith='Hello') 
    9393[<Article: Hello and goodbye>] 
     94 
     95# Q objects can be negated 
     96>>> Article.objects.filter(Q(pk=1) | ~Q(pk=2)) 
     97[<Article: Hello>, <Article: Hello and goodbye>] 
     98>>> Article.objects.filter(~Q(pk=1) & ~Q(pk=2)) 
     99[<Article: Hello and goodbye>] 
     100 
     101# This allows for more complex queries than filter() and exclude() alone would 
     102# allow 
     103>>> Article.objects.filter(Q(pk=1) & (~Q(pk=2) | Q(pk=3))) 
     104[<Article: Hello>] 
    94105 
    95106# Try some arg queries with operations other than filter. 
  • django/trunk/tests/modeltests/reserved_names/models.py

    r5876 r7477  
    4646>>> print v.where 
    47472005-01-01 
    48 >>> Thing.objects.order_by('select.when') 
    49 [<Thing: a>, <Thing: h>] 
    5048 
    5149>>> Thing.objects.dates('where', 'year') 
  • django/trunk/tests/modeltests/reverse_lookup/models.py

    r5876 r7477  
    5656Traceback (most recent call last): 
    5757    ... 
    58 TypeError: Cannot resolve keyword 'choice' into field. Choices are: poll_choice, related_choice, id, question, creator 
     58FieldError: Cannot resolve keyword 'choice' into field. Choices are: creator, id, poll_choice, question, related_choice 
    5959"""} 
  • django/trunk/tests/modeltests/select_related/models.py

    r6813 r7477  
    2828    def __unicode__(self): 
    2929        return self.name 
    30      
     30 
    3131class Klass(models.Model): 
    3232    name = models.CharField(max_length=50) 
     
    3434    def __unicode__(self): 
    3535        return self.name 
    36      
     36 
    3737class Order(models.Model): 
    3838    name = models.CharField(max_length=50) 
     
    6464    models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species] 
    6565    assert len(names) == len(models), (names, models) 
    66      
     66 
    6767    parent = None 
    6868    for name, model in zip(names, models): 
     
    101101# However, a select_related() call will fill in those related objects without any extra queries: 
    102102>>> db.reset_queries() 
    103 >>> person = Species.objects.select_related().get(name="sapiens") 
     103>>> person = Species.objects.select_related(depth=10).get(name="sapiens") 
    104104>>> person.genus.family.order.klass.phylum.kingdom.domain 
    105105<Domain: Eukaryota> 
     
    130130<Domain: Eukaryota> 
    131131 
    132 # Notice: one few query than above because of depth=1 
     132# Notice: one fewer queries than above because of depth=1 
    133133>>> len(db.connection.queries) 
    1341347 
     
    1481485 
    149149 
     150>>> s = Species.objects.all().select_related(depth=1).extra(select={'a': 'select_related_species.id + 10'})[0] 
     151>>> s.id + 10 == s.a 
     152True 
     153 
     154# The optional fields passed to select_related() control which related models 
     155# we pull in. This allows for smaller queries and can act as an alternative 
     156# (or, in addition to) the depth parameter. 
     157 
     158# In the next two cases, we explicitly say to select the 'genus' and 
     159# 'genus.family' models, leading to the same number of queries as before. 
     160>>> db.reset_queries() 
     161>>> world = Species.objects.select_related('genus__family') 
     162>>> [o.genus.family for o in world] 
     163[<Family: Drosophilidae>, <Family: Hominidae>, <Family: Fabaceae>, <Family: Amanitacae>] 
     164>>> len(db.connection.queries) 
     1651 
     166 
     167>>> db.reset_queries() 
     168>>> world = Species.objects.filter(genus__name='Amanita').select_related('genus__family') 
     169>>> [o.genus.family.order for o in world] 
     170[<Order: Agaricales>] 
     171>>> len(db.connection.queries) 
     1722 
     173 
     174>>> db.reset_queries() 
     175>>> Species.objects.all().select_related('genus__family__order').order_by('id')[0:1].get().genus.family.order.name 
     176u'Diptera' 
     177>>> len(db.connection.queries) 
     1781 
     179 
     180# Specifying both "depth" and fields is an error. 
     181>>> Species.objects.select_related('genus__family__order', depth=4) 
     182Traceback (most recent call last): 
     183... 
     184TypeError: Cannot pass both "depth" and fields to select_related() 
     185 
    150186# Reset DEBUG to where we found it. 
    151187>>> settings.DEBUG = False 
    152188"""} 
     189 
  • django/trunk/tests/modeltests/serializers/models.py

    r6891 r7477  
    2323    class Meta: 
    2424        ordering = ('name',) 
    25      
     25 
    2626    def __unicode__(self): 
    2727        return self.name 
     
    4040 
    4141class AuthorProfile(models.Model): 
    42     author = models.OneToOneField(Author
     42    author = models.OneToOneField(Author, primary_key=True
    4343    date_of_birth = models.DateField() 
    44      
     44 
    4545    def __unicode__(self): 
    4646        return u"Profile of %s" % self.author 
    47          
     47 
    4848class Actor(models.Model): 
    4949    name = models.CharField(max_length=20, primary_key=True) 
     
    5151    class Meta: 
    5252        ordering = ('name',) 
    53      
     53 
    5454    def __unicode__(self): 
    5555        return self.name 
    56      
     56 
    5757class Movie(models.Model): 
    5858    actor = models.ForeignKey(Actor) 
     
    6464    def __unicode__(self): 
    6565        return self.title 
    66          
     66 
    6767class Score(models.Model): 
    6868    score = models.FloatField() 
     
    101101 
    102102# Deserializing has a similar interface, except that special DeserializedObject 
    103 # instances are returned.  This is because data might have changed in the  
     103# instances are returned.  This is because data might have changed in the 
    104104# database since the data was serialized (we'll simulate that below). 
    105105>>> for obj in serializers.deserialize("xml", xml): 
     
    149149[<Article: Just kidding; I love TV poker>, <Article: Time to reform copyright>] 
    150150 
    151 # If you use your own primary key field (such as a OneToOneField),  
     151# If you use your own primary key field (such as a OneToOneField), 
    152152# it doesn't appear in the serialized field list - it replaces the 
    153153# pk identifier. 
     
    187187[{"pk": 1, "model": "serializers.article", "fields": {"headline": "Just kidding; I love TV poker", "pub_date": "2006-06-16 11:00:00"}}, {"pk": 2, "model": "serializers.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:11"}}, {"pk": 3, "model": "serializers.article", "fields": {"headline": "Forward references pose no problem", "pub_date": "2006-06-16 15:00:00"}}] 
    188188 
    189 # Every string is serialized as a unicode object, also primary key  
     189# Every string is serialized as a unicode object, also primary key 
    190190# which is 'varchar' 
    191191>>> ac = Actor(name="Zażółć") 
     
    248248<BLANKLINE> 
    249249 
    250 >>> obs = list(serializers.deserialize("yaml", serialized))  
    251 >>> for i in obs:  
     250>>> obs = list(serializers.deserialize("yaml", serialized)) 
     251>>> for i in obs: 
    252252...     print i 
    253253<DeserializedObject: Just kidding; I love TV poker> 
     
    255255 
    256256""" 
    257 except ImportError: pass 
    258      
     257except ImportError: 
     258    pass 
     259 
  • django/trunk/tests/modeltests/signals/models.py

    r7294 r7477  
    6767Is updated 
    6868 
    69 >>> p1.save(raw=True) 
     69# Calling an internal method purely so that we can trigger a "raw" save. 
     70>>> p1.save_base(raw=True) 
    7071pre_save_nokwargs signal 
    7172pre_save signal, Tom Smith 
  • django/trunk/tests/modeltests/transactions/models.py

    r5876 r7477  
    2626building_docs = getattr(settings, 'BUILDING_DOCS', False) 
    2727 
    28 if building_docs or settings.DATABASE_ENGINE != 'mysql'
     28if building_docs or settings.DATABASE_ENGINE not in ('mysql', 'mysql_old')
    2929    __test__['API_TESTS'] += """ 
    3030# the default behavior is to autocommit after each save() action