2013-04-15 70 views
0

我有模式:如何處理Django的多對多映射對象

class tags(models.Model): 
    """ This is the tag model """ 
    tag = models.CharField(max_length=15)    # Tag name 
    tagDescription = models.TextField()     # Tag Description 
    tagSlug = models.CharField(max_length=400)   # Extra info can be added to the existing tag using this field 
    createdAt = models.DateTimeField(auto_now_add=True) 
    updatedAt = models.DateTimeField(auto_now=True) 
    def __unicode__(self): 
     return unicode(self.tag) 


class stores(models.Model): 
    """ This is the store model """ 
    storeName = models.CharField(max_length=15)           # Store Name 
    storeDescription = models.TextField()            # Store Description 
    storeURL = models.URLField()               # Store URL 
    storePopularityNumber = models.IntegerField(max_length=1)       # Store Popularity Number 
    storeImage = models.ImageField(upload_to=storeImageDir)        # Store Image 
    storeSlug = models.CharField(max_length=400)              # This is the text you see in the URL 
    createdAt = models.DateTimeField(auto_now_add=True)             # Time at which store is created 
    updatedAt = models.DateTimeField(auto_now=True)             # Time at which store is updated 
    storeTags = models.ManyToManyField(tags)            # All the tags associated with the store 
    def __unicode__(self): 
     return unicode(self.storeName) 

    def StoreTags(self): 
     return unicode(self.storeTags.all()) 

據StoreTags 下顯示[]這是storesAdmin類:

class storesAdmin(admin.ModelAdmin): 
    list_display = ('storeName','storeDescription','storeURL', 
        'storePopularityNumber','storeImage', 
        'storeSlug','createdAt','createdAt','StoreTags' 
        ) 

爲什麼它會顯示這樣的我甚至試圖將其轉換成unicode,但它不工作。

回答

1

避免在模型字段中使用CamelCase。 Django Codigo Style - Model Field

「字段名稱應該全部小寫,使用下劃線而不是camelCase。」

避免在函數和方法中使用CamelCase。

「對變量,函數和方法名稱使用下劃線而非camelCase(即poll.get_unique_voters(),而不是poll.getUniqueVoters)」。

嘗試爲storetags方法選擇另一個名稱。也許這與storetags場擦出name.django哈希對象

+1

對於pep8警告+1。 – alix

0

嘗試用代碼:

models 
class Tags(models.Model): 
    #... 
    def __unicode__(self): 
     return '%s' % self.tag 

class Stores(models.Model): 
    #... 
    def __unicode__(self): 
     return '%s' % self.storeTags.tag 

admin, list_display is not supported to ManyToMany, i'm remove storetags 
class storesAdmin(admin.ModelAdmin): 
    list_display = ('storename','storedescription','storeurl', 
       'storepopularitynumber','storeimage', 
       'storeslug','createdat','createdat' 
       ) 

告訴我,如果它工作正常。

+0

我正在更新我的答案。 –

+1

試試這個:def StoreTags(self): return'\ n'.join([s.tag for s in self.storeTags.all()]) – 2013-04-16 05:02:45