2017-01-02 28 views
3

我有一個簡單的關係模型,用戶可以像使用stackoverflow一樣跟隨標籤。通過django中的字段查詢中間

class Relation(models.Model): 
    user = AutoOneToOneField(User) 
    follows_tag = models.ManyToManyField(Tag, blank=True, null=True, through='TagRelation') 

class TagRelation(models.Model): 
    user = models.ForeignKey(Relation, on_delete=models.CASCADE) 
    following_tag = models.ForeignKey(Tag, on_delete=models.CASCADE) 
    pub_date = models.DateTimeField(default=timezone.now) 

    class Meta: 
     unique_together = ['user', 'following_tag'] 

現在,把所有的標籤結果的用戶以下內容:

kakar = CustomUser.objects.get(email="[email protected]") 
tags_following = kakar.relation.follows_tag.all() 

這是好的。

但是,要訪問中間字段,我必須通過其他查詢的大名單。假設我要顯示當用戶開始關注一個標籤,我將不得不做這樣的事情:

kakar = CustomUser.objects.get(email="[email protected]") 
kakar_relation = Relation.objects.get(user=kakar) 
t1 = kakar.relation.follows_tag.all()[0] 
kakar_t1_relation = TagRelation.objects.get(user=kakar_relation, following_tag=t1) 
kakar_t1_relation.pub_date 

正如你所看到的,只是爲了讓我必須去經歷了這麼多的查詢日期。這是獲得中間值的唯一方法,還是可以優化?另外,我不確定這種模型設計是否可行,所以如果您有任何推薦或建議,我將非常感激。謝謝。

回答

1

您需要使用雙下劃線即(__)爲ForeignKey的查找, 像這樣:

user_tags = TagRelation.objects.filter(user__user__email="[email protected]").values("following_tag__name", "pub_date") 

如果你需要標記的名稱,你可以在查詢,如果您使用following_tag__name需要身份證,您可以使用following_tag__id

爲此,你需要通過上面的查詢集合的結果進行迭代,就像這樣:

for items in user_tags: 
    print items['following_tag__name'] 
    print items['pub_date'] 

一兩件事,關鍵的詞將返回詞典,您可以列表通過上述方法迭代它,並且如果您正在使用values_list代替,它將返回元組列表Read further from here

相關問題