code_junkie

Can I use a ForeignKey in __unicode__ return?

Nov 13th, 2011
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. class Ingredient(models.Model):
  2. name = models.CharField(max_length=30, primary_key=True)
  3. qty_on_stock = models.IntegerField()
  4.  
  5. def __unicode__(self):
  6. return self.name
  7.  
  8. class Recipe(models.Model):
  9. name = models.CharField(max_length=30, primary_key=True)
  10. comments = models.TextField(blank=True)
  11. ingredient = models.ManyToManyField(Ingredient)
  12.  
  13. def __unicode__(self):
  14. return self.name
  15.  
  16. class RecipeContent(models.Model):
  17. recipe = models.ForeignKey(Recipe)
  18. ingredients = models.ForeignKey(Ingredient)
  19. qty_used = models.IntegerField()
  20.  
  21. class RecipeContent(models.Model):
  22. ...
  23. def __unicode__(self):
  24. # You can access ForeignKey properties through the field name!
  25. return self.recipe.name
  26.  
  27. class Recipe(models.Model):
  28. name = models.CharField(max_length=30, primary_key=True)
  29. comments = models.TextField(blank=True)
  30. ...
  31.  
  32. def __unicode__(self):
  33. return self.name
  34.  
  35. class RecipeContent(models.Model):
  36. recipe = models.ForeignKey(Recipe)
  37. ...
  38.  
  39. def __unicode__(self):
  40. return str(self.recipe)
Add Comment
Please, Sign In to add comment