Changeset 7477 for django/trunk/tests/modeltests
- Timestamp:
- 04/26/08 21:50:16 (9 months ago)
- Files:
-
- django/trunk/tests/modeltests/basic/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/custom_columns/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/field_subclassing/models.py (modified) (3 diffs)
- django/trunk/tests/modeltests/lookup/models.py (modified) (3 diffs)
- django/trunk/tests/modeltests/many_to_many/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/many_to_one/models.py (modified) (4 diffs)
- django/trunk/tests/modeltests/many_to_one_null/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/model_inheritance/models.py (modified) (4 diffs)
- django/trunk/tests/modeltests/one_to_one/models.py (modified) (7 diffs)
- django/trunk/tests/modeltests/ordering/models.py (modified) (2 diffs)
- django/trunk/tests/modeltests/order_with_respect_to (added)
- django/trunk/tests/modeltests/order_with_respect_to/__init__.py (added)
- django/trunk/tests/modeltests/order_with_respect_to/models.py (added)
- django/trunk/tests/modeltests/or_lookups/models.py (modified) (3 diffs)
- django/trunk/tests/modeltests/reserved_names/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/reverse_lookup/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/select_related/models.py (modified) (6 diffs)
- django/trunk/tests/modeltests/serializers/models.py (modified) (9 diffs)
- django/trunk/tests/modeltests/signals/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/transactions/models.py (modified) (1 diff)
- django/trunk/tests/modeltests/update (added)
- django/trunk/tests/modeltests/update/__init__.py (added)
- django/trunk/tests/modeltests/update/models.py (added)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/trunk/tests/modeltests/basic/models.py
r7132 r7477 293 293 [<Article: Default headline>] 294 294 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>] 300 298 301 299 # Also, once you have sliced you can't filter, re-order or combine django/trunk/tests/modeltests/custom_columns/models.py
r5876 r7477 56 56 >>> art.authors = [a, a2] 57 57 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... 60 60 61 61 # Query the available authors … … 72 72 Traceback (most recent call last): 73 73 ... 74 TypeError: Cannot resolve keyword 'firstname' into field. Choices are: article, id, first_name, last_name74 FieldError: Cannot resolve keyword 'firstname' into field. Choices are: article, first_name, id, last_name 75 75 76 76 >>> a = Author.objects.get(last_name__exact='Smith') django/trunk/tests/modeltests/field_subclassing/models.py
r7294 r7477 6 6 from django.utils.encoding import force_unicode 7 7 from django.core import serializers 8 from django.core.exceptions import FieldError 8 9 9 10 class Small(object): … … 51 52 if lookup_type == 'isnull': 52 53 return [] 53 raise TypeError('Invalid lookup type: %r' % lookup_type)54 raise FieldError('Invalid lookup type: %r' % lookup_type) 54 55 55 56 def flatten_data(self, follow, obj=None): … … 95 96 Traceback (most recent call last): 96 97 ... 97 TypeError: Invalid lookup type: 'lt'98 FieldError: Invalid lookup type: 'lt' 98 99 99 100 # Serialization works, too. django/trunk/tests/modeltests/lookup/models.py
r7322 r7477 163 163 Traceback (most recent call last): 164 164 ... 165 Field DoesNotExist: Article has no field named 'id_plus_two'165 FieldError: Cannot resolve keyword 'id_plus_two' into field. Choices are: headline, id, id_plus_one, pub_date 166 166 167 167 # If you don't specify field names to values(), all are returned. 168 168 >>> list(Article.objects.filter(id=5).values()) == [{'id': 5, 'headline': 'Article 5', 'pub_date': datetime(2005, 8, 1, 9, 0)}] 169 169 True 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) 191 Traceback (most recent call last): 192 ... 193 TypeError: 'flat' is not valid when values_list is called with more than one field. 170 194 171 195 # Every DateField and DateTimeField creates get_next_by_FOO() and … … 241 265 >>> Article.objects.none().filter(headline__startswith='Article') 242 266 [] 267 >>> Article.objects.filter(headline__startswith='Article').none() 268 [] 243 269 >>> Article.objects.none().count() 244 270 0 … … 257 283 Traceback (most recent call last): 258 284 ... 259 TypeError: Cannot resolve keyword 'pub_date_year' into field. Choices are: id, headline, pub_date285 FieldError: Cannot resolve keyword 'pub_date_year' into field. Choices are: headline, id, pub_date 260 286 261 287 >>> Article.objects.filter(headline__starts='Article') 262 288 Traceback (most recent call last): 263 289 ... 264 TypeError: Cannot resolve keyword 'headline__starts' into field. Choices are: id, headline, pub_date 290 FieldError: Join on field 'headline' not permitted. 265 291 266 292 # Create some articles with a bit more interesting headlines for testing field lookups: django/trunk/tests/modeltests/many_to_many/models.py
r5876 r7477 127 127 [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>] 128 128 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 129 134 # If we delete a Publication, its Articles won't be able to access it. 130 135 >>> p1.delete() django/trunk/tests/modeltests/many_to_one/models.py
r5876 r7477 146 146 147 147 # 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] 150 150 >>> sql.count('INNER JOIN') 151 151 1 152 152 153 153 # 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'"]) 155 155 [<Article: John's second story>, <Article: This is a test>] 156 156 157 157 # And should work fine with the unicode that comes out of 158 158 # 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']) 160 160 [<Article: John's second story>, <Article: This is a test>] 161 161 … … 180 180 Traceback (most recent call last): 181 181 ... 182 TypeError: Cannot resolve keyword 'reporter_id' into field. Choices are: id, headline, pub_date, reporter182 FieldError: Cannot resolve keyword 'reporter_id' into field. Choices are: headline, id, pub_date, reporter 183 183 184 184 # You need to specify a comparison clause … … 186 186 Traceback (most recent call last): 187 187 ... 188 TypeError: Cannot resolve keyword 'reporter_id' into field. Choices are: id, headline, pub_date, reporter188 FieldError: Cannot resolve keyword 'reporter_id' into field. Choices are: headline, id, pub_date, reporter 189 189 190 190 # You can also instantiate an Article by passing … … 250 250 >>> Reporter.objects.filter(article__reporter=r).distinct() 251 251 [<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] 256 True 252 257 253 258 # If you delete a reporter, his articles will be deleted. django/trunk/tests/modeltests/many_to_one_null/models.py
r5876 r7477 81 81 [<Article: Third>] 82 82 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 83 88 # Set the reporter for the Third article 84 89 >>> r.article_set.add(a3) django/trunk/tests/modeltests/model_inheritance/models.py
r5876 r7477 2 2 XX. Model inheritance 3 3 4 Model inheritance isn't yet supported. 4 Model 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 12 Both styles are demonstrated here. 5 13 """ 6 14 7 15 from django.db import models 16 17 # 18 # Abstract base classes 19 # 20 21 class 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 32 class Worker(CommonInfo): 33 job = models.CharField(max_length=50) 34 35 class Student(CommonInfo): 36 school_class = models.CharField(max_length=10) 37 38 class Meta: 39 pass 40 41 # 42 # Multi-table inheritance 43 # 44 45 class Chef(models.Model): 46 name = models.CharField(max_length=50) 47 48 def __unicode__(self): 49 return u"%s the chef" % self.name 8 50 9 51 class Place(models.Model): … … 14 56 return u"%s the place" % self.name 15 57 16 class Restaurant(Place): 58 class Rating(models.Model): 59 rating = models.IntegerField(null=True, blank=True) 60 61 class Meta: 62 abstract = True 63 ordering = ['-rating'] 64 65 class Restaurant(Place, Rating): 17 66 serves_hot_dogs = models.BooleanField() 18 67 serves_pizza = models.BooleanField() 68 chef = models.ForeignKey(Chef, null=True, blank=True) 69 70 class Meta(Rating.Meta): 71 db_table = 'my_restaurant' 19 72 20 73 def __unicode__(self): … … 27 80 return u"%s the italian restaurant" % self.name 28 81 82 class Supplier(Place): 83 customers = models.ManyToManyField(Restaurant, related_name='provider') 84 85 def __unicode__(self): 86 return u"%s the supplier" % self.name 87 88 class 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 29 96 __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) 110 u'Worker Fred' 111 >>> unicode(s) 112 u'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() 127 Traceback (most recent call last): 128 ... 129 AttributeError: 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. 37 134 38 135 # Create a couple of Places. … … 42 139 >>> p2.save() 43 140 44 #Test constructor for Restaurant.45 >>> r = Restaurant(name='Demon Dogs', address='944 W. Fullerton', serves_hot_dogs=True, serves_pizza=False)141 Test constructor for Restaurant. 142 >>> r = Restaurant(name='Demon Dogs', address='944 W. Fullerton',serves_hot_dogs=True, serves_pizza=False, rating=2) 46 143 >>> r.save() 47 144 48 145 # 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) 50 149 >>> 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') 168 Traceback (most recent call last): 169 ... 170 FieldError: 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 197 Traceback (most recent call last): 198 ... 199 DoesNotExist: 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 214 Traceback (most recent call last): 215 ... 216 DoesNotExist: 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 243 True 244 >>> r1.name 245 u'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] 250 True 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 2 262 >>> ItalianRestaurant.objects.select_related('chef')[0].chef 263 <Chef: Albert the chef> 264 >>> len(db.connection.queries) 265 3 266 >>> settings.DEBUG = False 52 267 53 268 """} django/trunk/tests/modeltests/one_to_one/models.py
r5876 r7477 7 7 """ 8 8 9 from django.db import models 9 from django.db import models, connection 10 10 11 11 class Place(models.Model): … … 17 17 18 18 class Restaurant(models.Model): 19 place = models.OneToOneField(Place )19 place = models.OneToOneField(Place, primary_key=True) 20 20 serves_hot_dogs = models.BooleanField() 21 21 serves_pizza = models.BooleanField() … … 38 38 link = models.OneToOneField(ManualPrimaryKey) 39 39 name = models.CharField(max_length = 50) 40 41 class 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 40 48 41 49 __test__ = {'API_TESTS':""" … … 64 72 DoesNotExist: Restaurant matching query does not exist. 65 73 66 # Set the place using assignment notation. Because place is the primary key on Restaurant,67 # the save will create a new restaurant74 # Set the place using assignment notation. Because place is the primary key on 75 # Restaurant, the save will create a new restaurant 68 76 >>> r.place = p2 69 77 >>> r.save() … … 73 81 <Place: Ace Hardware the place> 74 82 75 # Set the place back again, using assignment in the reverse direction 76 # Need to reget restaurant object first, because the reverse set77 # can't update theexisting restaurant instance83 # 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 78 86 >>> p1.restaurant = r 79 87 >>> r.save() … … 87 95 # Restaurant.objects.all() just returns the Restaurants, not the Places. 88 96 # 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. 91 98 >>> Restaurant.objects.all() 92 99 [<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>] … … 166 173 >>> o2 = RelatedModel(link=o1, name="secondary") 167 174 >>> 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() 185 Traceback (most recent call last): 186 ... 187 IntegrityError: ... 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() 168 193 """} django/trunk/tests/modeltests/ordering/models.py
r7119 r7477 49 49 [<Article: Article 1>, <Article: Article 3>, <Article: Article 2>, <Article: Article 4>] 50 50 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 51 58 # Use the 'stop' part of slicing notation to limit the results. 52 59 >>> Article.objects.order_by('headline')[:2] … … 65 72 >>> Article.objects.order_by('?') 66 73 [...] 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>] 67 80 """} django/trunk/tests/modeltests/or_lookups/models.py
r7379 r7477 5 5 combine QuerySet objects using & and | operators. 6 6 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 7 Alternatively, use positional arguments, and pass one or more expressions of 8 clauses using the variable ``django.db.models.Q`` (or any object with an 9 add_to_query method). 12 10 """ 13 11 … … 73 71 >>> Article.objects.filter(pk__in=[1,2,3]) 74 72 [<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>] 75 75 76 76 >>> Article.objects.filter(pk__in=[1,2,3,4]) … … 92 92 >>> Article.objects.filter(Q(headline__contains='bye'), headline__startswith='Hello') 93 93 [<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>] 94 105 95 106 # Try some arg queries with operations other than filter. django/trunk/tests/modeltests/reserved_names/models.py
r5876 r7477 46 46 >>> print v.where 47 47 2005-01-01 48 >>> Thing.objects.order_by('select.when')49 [<Thing: a>, <Thing: h>]50 48 51 49 >>> Thing.objects.dates('where', 'year') django/trunk/tests/modeltests/reverse_lookup/models.py
r5876 r7477 56 56 Traceback (most recent call last): 57 57 ... 58 TypeError: Cannot resolve keyword 'choice' into field. Choices are: poll_choice, related_choice, id, question, creator 58 FieldError: Cannot resolve keyword 'choice' into field. Choices are: creator, id, poll_choice, question, related_choice 59 59 """} django/trunk/tests/modeltests/select_related/models.py
r6813 r7477 28 28 def __unicode__(self): 29 29 return self.name 30 30 31 31 class Klass(models.Model): 32 32 name = models.CharField(max_length=50) … … 34 34 def __unicode__(self): 35 35 return self.name 36 36 37 37 class Order(models.Model): 38 38 name = models.CharField(max_length=50) … … 64 64 models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species] 65 65 assert len(names) == len(models), (names, models) 66 66 67 67 parent = None 68 68 for name, model in zip(names, models): … … 101 101 # However, a select_related() call will fill in those related objects without any extra queries: 102 102 >>> db.reset_queries() 103 >>> person = Species.objects.select_related( ).get(name="sapiens")103 >>> person = Species.objects.select_related(depth=10).get(name="sapiens") 104 104 >>> person.genus.family.order.klass.phylum.kingdom.domain 105 105 <Domain: Eukaryota> … … 130 130 <Domain: Eukaryota> 131 131 132 # Notice: one few querythan above because of depth=1132 # Notice: one fewer queries than above because of depth=1 133 133 >>> len(db.connection.queries) 134 134 7 … … 148 148 5 149 149 150 >>> s = Species.objects.all().select_related(depth=1).extra(select={'a': 'select_related_species.id + 10'})[0] 151 >>> s.id + 10 == s.a 152 True 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) 165 1 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) 172 2 173 174 >>> db.reset_queries() 175 >>> Species.objects.all().select_related('genus__family__order').order_by('id')[0:1].get().genus.family.order.name 176 u'Diptera' 177 >>> len(db.connection.queries) 178 1 179 180 # Specifying both "depth" and fields is an error. 181 >>> Species.objects.select_related('genus__family__order', depth=4) 182 Traceback (most recent call last): 183 ... 184 TypeError: Cannot pass both "depth" and fields to select_related() 185 150 186 # Reset DEBUG to where we found it. 151 187 >>> settings.DEBUG = False 152 188 """} 189 django/trunk/tests/modeltests/serializers/models.py
r6891 r7477 23 23 class Meta: 24 24 ordering = ('name',) 25 25 26 26 def __unicode__(self): 27 27 return self.name … … 40 40 41 41 class AuthorProfile(models.Model): 42 author = models.OneToOneField(Author )42 author = models.OneToOneField(Author, primary_key=True) 43 43 date_of_birth = models.DateField() 44 44 45 45 def __unicode__(self): 46 46 return u"Profile of %s" % self.author 47 47 48 48 class Actor(models.Model): 49 49 name = models.CharField(max_length=20, primary_key=True) … … 51 51 class Meta: 52 52 ordering = ('name',) 53 53 54 54 def __unicode__(self): 55 55 return self.name 56 56 57 57 class Movie(models.Model): 58 58 actor = models.ForeignKey(Actor) … … 64 64 def __unicode__(self): 65 65 return self.title 66 66 67 67 class Score(models.Model): 68 68 score = models.FloatField() … … 101 101 102 102 # 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 104 104 # database since the data was serialized (we'll simulate that below). 105 105 >>> for obj in serializers.deserialize("xml", xml): … … 149 149 [<Article: Just kidding; I love TV poker>, <Article: Time to reform copyright>] 150 150 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), 152 152 # it doesn't appear in the serialized field list - it replaces the 153 153 # pk identifier. … … 187 187 [{"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"}}] 188 188 189 # Every string is serialized as a unicode object, also primary key 189 # Every string is serialized as a unicode object, also primary key 190 190 # which is 'varchar' 191 191 >>> ac = Actor(name="Zażółć") … … 248 248 <BLANKLINE> 249 249 250 >>> obs = list(serializers.deserialize("yaml", serialized)) 251 >>> for i in obs: 250 >>> obs = list(serializers.deserialize("yaml", serialized)) 251 >>> for i in obs: 252 252 ... print i 253 253 <DeserializedObject: Just kidding; I love TV poker> … … 255 255 256 256 """ 257 except ImportError: pass 258 257 except ImportError: 258 pass 259 django/trunk/tests/modeltests/signals/models.py
r7294 r7477 67 67 Is updated 68 68 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) 70 71 pre_save_nokwargs signal 71 72 pre_save signal, Tom Smith django/trunk/tests/modeltests/transactions/models.py
r5876 r7477 26 26 building_docs = getattr(settings, 'BUILDING_DOCS', False) 27 27 28 if building_docs or settings.DATABASE_ENGINE != 'mysql':28 if building_docs or settings.DATABASE_ENGINE not in ('mysql', 'mysql_old'): 29 29 __test__['API_TESTS'] += """ 30 30 # the default behavior is to autocommit after each save() action
