2008-12-27 36 views
12

Tôi có các lớp sau: Thành phần, công thức và RecipeContent ...Tôi có thể sử dụng ForeignKey trong __unicode__ không?

class Ingredient(models.Model): 
    name = models.CharField(max_length=30, primary_key=True) 
    qty_on_stock = models.IntegerField() 

    def __unicode__(self): 
     return self.name 

class Recipe(models.Model): 
    name = models.CharField(max_length=30, primary_key=True) 
    comments = models.TextField(blank=True) 
    ingredient = models.ManyToManyField(Ingredient) 

    def __unicode__(self): 
     return self.name 

class RecipeContent(models.Model): 
    recipe = models.ForeignKey(Recipe) 
    ingredients = models.ForeignKey(Ingredient) 
    qty_used = models.IntegerField() 

nhưng đối với __unicode __() trong RecipeContent Tôi muốn sử dụng tên Recipe mà RecipeContent này thuộc về ... là có một cách để làm điều đó?

+0

Chỉ cần lưu ý về kiểu, tôi khuyên bạn không nên đa nguyên tên trường ForeignKey vì chúng chỉ có thể trỏ đến một bản ghi tại một thời điểm. Tôi đang đề cập đến lĩnh vực thành phần của bạn dưới RecipeContent. – Soviut

Trả lời

26
class RecipeContent(models.Model): 
    ... 
    def __unicode__(self): 
    # You can access ForeignKey properties through the field name! 
    return self.recipe.name 
+0

thở dài ... nó thật đơn giản! cho thấy những gì một noob tôi ... Cảm ơn câu trả lời. – EroSan

+1

Sử dụng Django 1.6. Tôi nhận được: đối tượng 'NoneType' không có tên 'thuộc tính'. Phương thức: def __unicode __ (self): return self.instrument.name. Và: class Instrument (models.Model): name = models.CharField (max_length = 200). Và nơi tôi gọi là "unicode": instrument = models.ForeignKey (Instrument, null = True, blank = True) – Timo

+0

Tôi cũng nhận được điều này. Tôi khá là điều này xảy ra khi một số trường hợp có điều này trong khi một số thì không. Tôi đã phải tuôn ra. – Ryan

0

Có, bạn có thể (làm điểm bishanty), nhưng được chuẩn bị sẵn sàng cho trường hợp khi __unicode__() được gọi nhưng chưa được đặt. Tôi đã đến đây vài lần.

+0

true ... nhưng có lẽ tôi có thể đối phó với điều đó bằng cách sử dụng một cái gì đó dọc theo dòng "nếu self.recipe.name: return self.recipe.name"? – EroSan

2

Nếu bạn chỉ quan tâm đến phần tên của Recipe, bạn có thể làm:

class Recipe(models.Model): 
    name = models.CharField(max_length=30, primary_key=True) 
    comments = models.TextField(blank=True) 
    ... 

    def __unicode__(self): 
     return self.name 

class RecipeContent(models.Model): 
    recipe = models.ForeignKey(Recipe) 
    ... 

    def __unicode__(self): 
     return str(self.recipe) 
0

Trong Python 3 không có __unicode__, bạn cần phải sử dụng __str__ để thay thế.

class RecipeContent(models.Model): 
     ... 
     def __str__(self): 
      return self.recipe.name 
Các vấn đề liên quan