2012-09-28 55 views
0

我想創建一個模型方法,它將採用給定評論的 的「用戶」(這是CharField),然後返回與UserProfile的 部分定義的用戶關聯的「報價」。我正在嘗試創建方法以及模板。我迄今爲止嘗試過的東西似乎沒有奏效。如何編寫引用另一個模型的模型方法?

我知道最好的做法是讓 的用戶字段回覆給用戶,但我想知道如何用 方法做到這一點,這樣我就可以學習。

models.py

class Reviewbackup(models.Model): 
    review = models.CharField('Review', max_length = 2000) 
    user = models.CharField('Username', max_length = 200) 
    rating = models.IntegerField(max_length=2, choices=RATING_OPTIONS) 
    product = models.ForeignKey(Productbackup) 
    def __unicode__(self): 
     return self.review 

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    quote = models.CharField('About', max_length = 200, null=True, blank=True) 
    website = models.URLField('Personal website/blog', null=True, blank=True) 
    facebook = models.URLField('Facebook profile page', max_length = 200, null=True, blank=True) 
    twitter = models.URLField('Twitter profile page', max_length = 200, null=True, blank=True) 
    youtube = models.URLField('YouTube channel page', max_length = 200, null=True, blank=True) 

views.py

def view_reviews(request, product_name): 
    product = get_object_or_404(Productbackup, url_friendly=product_name) 
    product_id = product.id 
    #get reviews for the this product 
    reviews = Reviewbackup.objects.filter(product_id=product_id).order_by("-created_on") 
    return render_to_response('reserve/templates/view_reviews.html', {'reviews':reviews}, 
     context_instance=RequestContext(request)) 

模板

{% for review in reviews %} 
{{review.user}} 
<br>{{review.user.userprofile.quote}} 
{% endfor %} 
+0

你有沒有考慮尋找它在'User'? –

+0

@ IgnacioVazquez-Abrams你是什麼意思? – sharataka

回答

1

如果問題的條件說「不使用用戶一個ForeignKey,但使用CharField對於用戶名「,您可以將該方法添加到您的Reviewbackup模型中,例如:

def get_user_quote(self): 
    return UserProfile.objects.get(user__username=self.user).quote 

,並在模板中使用它:

{{ review.get_user_quote }} 

但你真的應該更換你的用戶領域外鍵

+0

謝謝@Dima。我意識到使它成爲一個ForeignKey會容易得多,但我正努力應對這一事實,即我的應用程序中已經有相當多的數據。你能幫我理解使用方法的缺點與ForeignKey相反嗎? – sharataka

+0

Reviewbackup數據庫表僅存儲用戶表中的用戶標識。默認情況下,它會有一個適當的索引,這樣連接表格的工作就會更快。 使用ForeignKey,您可以更容易地通過orm訪問數據,就像這種情況一樣:'{{review.user.userprofile.quote.quote}}'etc –

+0

如果我嘗試用ForeignKey(User)替換CharField,是否會產生影響關於我的應用中已有的數據?我是否必須重新裝入所有內容,因爲用戶以前是指字符串而不是對象? – sharataka

相關問題