code_junkie

How can one get the set of all classes with reverse relationships for a model in Django?

Nov 12th, 2011
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.53 KB | None | 0 0
  1. from django.db import models
  2.  
  3. class Food(models.Model):
  4. """Food, by name."""
  5. name = models.CharField(max_length=25)
  6.  
  7. class Cat(models.Model):
  8. """A cat eats one type of food"""
  9. food = models.ForeignKey(Food)
  10.  
  11. class Cow(models.Model):
  12. """A cow eats one type of food"""
  13. food = models.ForeignKey(Food)
  14.  
  15. class Human(models.Model):
  16. """A human may eat lots of types of food"""
  17. food = models.ManyToManyField(Food)
  18.  
  19. from django.db import models
  20. from django.contrib.contenttypes.models import ContentType
  21. from django.contrib.contenttypes import generic
  22.  
  23. class Food(models.Model):
  24. """Food, by name."""
  25. name = models.CharField(max_length=25)
  26.  
  27. # ConsumedFood has a foreign key to Food, and a "eaten_by" generic relation
  28. class ConsumedFood(models.Model):
  29. food = models.ForeignKey(Food, related_name="eaters")
  30. content_type = models.ForeignKey(ContentType, null=True)
  31. object_id = models.PositiveIntegerField(null=True)
  32. eaten_by = generic.GenericForeignKey('content_type', 'object_id')
  33.  
  34. class Person(models.Model):
  35. first_name = models.CharField(max_length=50)
  36. last_name = models.CharField(max_length=50)
  37. birth_date = models.DateField()
  38. address = models.CharField(max_length=100)
  39. city = models.CharField(max_length=50)
  40. foods = generic.GenericRelation(ConsumedFood)
  41.  
  42. class Cat(models.Model):
  43. name = models.CharField(max_length=50)
  44. foods = generic.GenericRelation(ConsumedFood)
  45.  
  46. class Cow(models.Model):
  47. farmer = models.ForeignKey(Person)
  48. foods = generic.GenericRelation(ConsumedFood)
  49.  
  50. """
  51. >>> from models import *
  52.  
  53. Create some food records
  54.  
  55. >>> weed = Food(name="weed")
  56. >>> weed.save()
  57.  
  58. >>> burger = Food(name="burger")
  59. >>> burger.save()
  60.  
  61. >>> pet_food = Food(name="Pet food")
  62. >>> pet_food.save()
  63.  
  64. John the farmer likes burgers
  65.  
  66. >>> john = Person(first_name="John", last_name="Farmer", birth_date="1960-10-12")
  67. >>> john.save()
  68. >>> john.foods.create(food=burger)
  69. <ConsumedFood: ConsumedFood object>
  70.  
  71. Wilma the cow eats weed
  72.  
  73. >>> wilma = Cow(farmer=john)
  74. >>> wilma.save()
  75. >>> wilma.foods.create(food=weed)
  76. <ConsumedFood: ConsumedFood object>
  77.  
  78. Felix the cat likes pet food
  79.  
  80. >>> felix = Cat(name="felix")
  81. >>> felix.save()
  82. >>> pet_food.eaters.create(eaten_by=felix)
  83. <ConsumedFood: ConsumedFood object>
  84.  
  85. What food john likes again ?
  86. >>> john.foods.all()[0].food.name
  87. u'burger'
  88.  
  89. Who's getting pet food ?
  90. >>> living_thing = pet_food.eaters.all()[0].eaten_by
  91. >>> isinstance(living_thing,Cow)
  92. False
  93. >>> isinstance(living_thing,Cat)
  94. True
  95.  
  96. John's farm is in fire ! He looses his cow.
  97. >>> wilma.delete()
  98.  
  99. John is a lot poorer right now
  100. >>> john.foods.clear()
  101. >>> john.foods.create(food=pet_food)
  102. <ConsumedFood: ConsumedFood object>
  103.  
  104. Who's eating pet food now ?
  105. >>> for consumed_food in pet_food.eaters.all():
  106. ... consumed_food.eaten_by
  107. <Cat: Cat object>
  108. <Person: Person object>
  109.  
  110. Get the second pet food eater
  111. >>> living_thing = pet_food.eaters.all()[1].eaten_by
  112.  
  113. Try to find if it's a person and reveal his name
  114. >>> if isinstance(living_thing,Person): living_thing.first_name
  115. u'John'
  116.  
  117. """
  118.  
  119. def get_all_related_objects(self, local_only=False):
  120.  
  121. def get_all_related_many_to_many_objects(self, local_only=False)
  122.  
  123. >>> Food._meta.get_all_related_objects()
  124. [<RelatedObject: app_label:cow related to food>,
  125. <RelatedObject: app_label:cat related to food>,]
  126.  
  127. >>> Food._meta.get_all_related_many_to_many_objects()
  128. [<RelatedObject: app_label:human related to food>,]
  129.  
  130. # and, per django/db/models/related.py
  131. # you can retrieve the model with
  132. >>> Food._meta.get_all_related_objects()[0].model
  133. <class 'app_label.models.Cow'>
Add Comment
Please, Sign In to add comment