2013-08-20 2 views
-2

Я пытаюсь использовать метод модели Django в представлениях.Как использовать методы модели Django в представлениях django

модели:

class stores(models.Model): 
    """ This is the store model """ 

    seo_url = models.URLField()               # SEO URL for flipdiscounts.in 
    storeURL = models.URLField()               # Store URL 
    fallBackURL = models.URLField()              # Fallback URL for couponURL   
    storeDescription = models.TextField()            # Store Description 
    storeTags = models.ManyToManyField(tags)            # All the tags associated with the store 
    storeName = models.CharField(max_length=30)           # Store Name 
    storeSlug = models.CharField(max_length=400)           # This is the text you see in the URL 
    updatedAt = models.DateTimeField(auto_now=True)          # Time at which store is updated 
    storeImage = models.ImageField(upload_to="images")         # Store Image 
    createdAt = models.DateTimeField(auto_now_add=True)         # Time at which store is created 
    hash = models.CharField(max_length=10,unique=True)         # Tag Hash for flipdisconts.in 
    storePopularityNumber = models.IntegerField(choices=PRIORITY_CHOICES,default=3)  # Store Popularity Number 


    def Store_Tags(self): 
     """Method to return tags related to store""" 
     return ','.join([t.tagSlug for t in self.storeTags.all()]) 

    def tagHash(self): 
     """Method to get tag hash related to store for flipdiscounts.in""" 
     return ','.join([t.hash for t in self.storeTags.all()]) 

    def store_URL(self): 
     """Method to return store URL for flipdiscounts.in""" 
     return self.seo_url + _storeURL + self.hash 

    def StoreCoupons(self): 
     """Method to return coupons related to store""" 
     for t in stores.objects.filter(storeName=self.storeName): 
      return ",".join([(a.couponTitle) for a in t.coupons_set.all()]) 

    def StoreCouponsId(self): 
     """Method to return coupons ID related to store""" 
     for t in stores.objects.filter(storeName=self.storeName): 
      return ",".join([str(a.id) for a in t.coupons_set.all()]) 

    def CouponsCount(self): 
     """Method to return coupons count related to store""" 
     for t in stores.objects.filter(storeName=self.storeName): 
      count = ",".join([str(a.id) for a in t.coupons_set.all()]) 
      count = count.split(',') 
      count = filter(None,count) 
      return len(count) 

    def StoreImage(self): 
     """Method to return store image for admin panel""" 
     return '<img src="/store%s" height="150" width="150"/>' % self.storeImage 
    StoreImage.allow_tags = True 

    def StoreURL(self): 
     """Method to return store URL""" 
     return '<a href="%(url)s" target="_blank">%(url)s</a>' %{"url":self.storeURL} 
    StoreURL.allow_tags = True 

    def imageURL(self): 
     """Method to return store Image related to store""" 
     return SERVER_ADDRESS + "store%s" % self.storeImage 

    class Meta: 
     """Meta class to control display Behavior of the Model name """ 
     verbose_name_plural = "Stores" 

    def __unicode__(self): 
     """Method to display string correctly""" 
     return unicode(self.storeName) 

    def save(self, *args, **kwargs): 

     self.hash = _generateHash()              # Generate Hash for flipdiscounts.in 
     self.seo_url = "discounts-in-" + self.storeName.replace(".","-")     # Generate SEO URL for flipdiscounts.in   
     super(stores, self).save(*args, **kwargs)  




class tags(models.Model): 
    """ This is the tag model """ 

    seo_url = models.URLField()             # SEO URL for flipdiscounts.in 
    tagDescription = models.TextField()           # Tag Description 
    tag = models.CharField(max_length=200)          # Tag name 
    tagSlug = models.CharField(max_length=400)         # Extra info can be added to the existing tag using this field 
    updatedAt = models.DateTimeField(auto_now=True)        # Time at which tag is updated 
    createdAt = models.DateTimeField(auto_now_add=True)       # Time at which tag is created 
    hash = models.CharField(max_length=10,unique=True)       # Tag Hash for flipdiscounts.in 

    def save(self, *args, **kwargs): 
     """Custom Save method for tags model """ 
     self.hash = _generateHash()             # Generate Hash for flipdiscounts.in 
     self.seo_url = "coupons-in-" + self.tagSlug.replace(".","-")    # Generate SEO URL for flipdiscounts.in   
     super(tags, self).save(*args, **kwargs)  

    def __unicode__(self): 
     """Method to display string correctly""" 
     return unicode(self.tag) 

    def storeNames(self): 
     """Method to get store related to tag""" 
     for t in tags.objects.filter(tag=self.tag): 
      return ",".join([str(a.storeName) for a in t.stores_set.all()]) 

    def storeHash(self): 
     """Method to get store hash related to tag for flipdiscounts.in""" 
     for t in tags.objects.filter(tag=self.tag): 
      return ",".join([str(a.hash) for a in t.stores_set.all()]) 

    def tagURL(self): 
     """Method to return tag URL for flipdiscounts.in""" 
     return self.seo_url + _tagURL + self.hash 

    def couponsId(self): 
     for t in tags.objects.filter(tag=self.tag): 
      for a in t.stores_set.all(): 
       return ",".join([str(i.id) for i in a.coupons_set.all()])      

    class Meta: 
     """Meta class to control display Behavior of the Model name """ 
     verbose_name_plural = "Tags" 

Как я могу использовать tags.storeNames() в моем views.py. Может кто-то пожалуйста, помогите мне

+1

Почему вы не можете просто назвать его? –

+0

Вы можете вызвать эту функцию для любого экземпляра объекта тегов класса. – Sudipta

+0

попытался сделать это, но получил 'tagStoresData = tags.storeNames() TypeError: unbound method storeNames() должен быть вызван с экземпляром тегов в качестве первого аргумента (вместо этого ничего не получается)' –

ответ

0
from appname.models import tags 

tagObj = tags() 
tagObj.storeNames() 
+0

Уже пробовал, что ... не работает –

+0

@Bartosz, который не будет работать, потому что методы ожидают вызова в фактическом сохраненном экземпляре (они ссылаются на различные отношения, которые не существовали бы в вашем коде). –

1

Это сработало:

for i in tags.objects.filter(): 
    print i.storeNames() 

Спасибо, ребята за кончиком ...

Смежные вопросы