PageRenderTime 17ms CodeModel.GetById 12ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/modeltests/generic_relations/models.py

https://code.google.com/p/mango-py/
Python | 80 lines | 44 code | 21 blank | 15 comment | 0 complexity | d436b497bddc69ebe8948bb989795ee3 MD5 | raw file
 1"""
 234. Generic relations
 3
 4Generic relations let an object have a foreign key to any object through a
 5content-type/object-id field. A ``GenericForeignKey`` field can point to any
 6object, be it animal, vegetable, or mineral.
 7
 8The canonical example is tags (although this example implementation is *far*
 9from complete).
10"""
11
12from django.contrib.contenttypes import generic
13from django.contrib.contenttypes.models import ContentType
14from django.db import models
15
16
17class TaggedItem(models.Model):
18    """A tag on an item."""
19    tag = models.SlugField()
20    content_type = models.ForeignKey(ContentType)
21    object_id = models.PositiveIntegerField()
22
23    content_object = generic.GenericForeignKey()
24
25    class Meta:
26        ordering = ["tag", "content_type__name"]
27
28    def __unicode__(self):
29        return self.tag
30
31class ValuableTaggedItem(TaggedItem):
32    value = models.PositiveIntegerField()
33
34class Comparison(models.Model):
35    """
36    A model that tests having multiple GenericForeignKeys
37    """
38    comparative = models.CharField(max_length=50)
39
40    content_type1 = models.ForeignKey(ContentType, related_name="comparative1_set")
41    object_id1 = models.PositiveIntegerField()
42
43    content_type2 = models.ForeignKey(ContentType,  related_name="comparative2_set")
44    object_id2 = models.PositiveIntegerField()
45
46    first_obj = generic.GenericForeignKey(ct_field="content_type1", fk_field="object_id1")
47    other_obj = generic.GenericForeignKey(ct_field="content_type2", fk_field="object_id2")
48
49    def __unicode__(self):
50        return u"%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj)
51
52class Animal(models.Model):
53    common_name = models.CharField(max_length=150)
54    latin_name = models.CharField(max_length=150)
55
56    tags = generic.GenericRelation(TaggedItem)
57    comparisons = generic.GenericRelation(Comparison,
58                                          object_id_field="object_id1",
59                                          content_type_field="content_type1")
60
61    def __unicode__(self):
62        return self.common_name
63
64class Vegetable(models.Model):
65    name = models.CharField(max_length=150)
66    is_yucky = models.BooleanField(default=True)
67
68    tags = generic.GenericRelation(TaggedItem)
69
70    def __unicode__(self):
71        return self.name
72
73class Mineral(models.Model):
74    name = models.CharField(max_length=150)
75    hardness = models.PositiveSmallIntegerField()
76
77    # note the lack of an explicit GenericRelation here...
78
79    def __unicode__(self):
80        return self.name