PageRenderTime 31ms CodeModel.GetById 0ms 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
Possible License(s): BSD-3-Clause
  1. """
  2. 34. Generic relations
  3. Generic relations let an object have a foreign key to any object through a
  4. content-type/object-id field. A ``GenericForeignKey`` field can point to any
  5. object, be it animal, vegetable, or mineral.
  6. The canonical example is tags (although this example implementation is *far*
  7. from complete).
  8. """
  9. from django.contrib.contenttypes import generic
  10. from django.contrib.contenttypes.models import ContentType
  11. from django.db import models
  12. class TaggedItem(models.Model):
  13. """A tag on an item."""
  14. tag = models.SlugField()
  15. content_type = models.ForeignKey(ContentType)
  16. object_id = models.PositiveIntegerField()
  17. content_object = generic.GenericForeignKey()
  18. class Meta:
  19. ordering = ["tag", "content_type__name"]
  20. def __unicode__(self):
  21. return self.tag
  22. class ValuableTaggedItem(TaggedItem):
  23. value = models.PositiveIntegerField()
  24. class Comparison(models.Model):
  25. """
  26. A model that tests having multiple GenericForeignKeys
  27. """
  28. comparative = models.CharField(max_length=50)
  29. content_type1 = models.ForeignKey(ContentType, related_name="comparative1_set")
  30. object_id1 = models.PositiveIntegerField()
  31. content_type2 = models.ForeignKey(ContentType, related_name="comparative2_set")
  32. object_id2 = models.PositiveIntegerField()
  33. first_obj = generic.GenericForeignKey(ct_field="content_type1", fk_field="object_id1")
  34. other_obj = generic.GenericForeignKey(ct_field="content_type2", fk_field="object_id2")
  35. def __unicode__(self):
  36. return u"%s is %s than %s" % (self.first_obj, self.comparative, self.other_obj)
  37. class Animal(models.Model):
  38. common_name = models.CharField(max_length=150)
  39. latin_name = models.CharField(max_length=150)
  40. tags = generic.GenericRelation(TaggedItem)
  41. comparisons = generic.GenericRelation(Comparison,
  42. object_id_field="object_id1",
  43. content_type_field="content_type1")
  44. def __unicode__(self):
  45. return self.common_name
  46. class Vegetable(models.Model):
  47. name = models.CharField(max_length=150)
  48. is_yucky = models.BooleanField(default=True)
  49. tags = generic.GenericRelation(TaggedItem)
  50. def __unicode__(self):
  51. return self.name
  52. class Mineral(models.Model):
  53. name = models.CharField(max_length=150)
  54. hardness = models.PositiveSmallIntegerField()
  55. # note the lack of an explicit GenericRelation here...
  56. def __unicode__(self):
  57. return self.name