如何在Django模型中对多对多关系进行排序

时间:2013-08-27 03:38:45

标签: python django django-models

我想根据优惠券的数量对标签进行排序。标签和商店模型具有多对多的关系,商店和优惠券具有一对多的关系。

my models.py:

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

    seo_url = models.URLField()                                                 # SEO URL for mypromocodes.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 mypromocodes.in

    def save(self, *args, **kwargs):
        """Custom Save method for tags model """
        self.hash = _generateHash()                                                 # Generate Hash for mypromocodes.in
        self.seo_url = "promocodes-in-" + self.tagSlug.replace(".","-")             # Generate SEO URL for mypromocodes.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 mypromocodes.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 mypromocodes.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"

#------------------------------------------------------------------------------ 

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

    seo_url = models.URLField()                                                          # SEO URL for mypromocodes.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 mypromocodes.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 mypromocodes.in"""
        return ','.join([t.hash for t in self.storeTags.all()])

    def store_URL(self):
        """Method to return store URL for mypromocodes.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="%s%s" height="150" width="150"/>' % (MEDIA_URL , 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 HOST_NAME + "%s%s" % (MEDIA_URL , 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 mypromocodes.in
        self.seo_url = "coupons-in-" + self.storeName.replace(".","-")                   # Generate SEO URL for mypromocodes.in        
        super(stores, self).save(*args, **kwargs)    
#------------------------------------------------------------------------------ 

class coupons(models.Model):
    """ This is the coupon model """

    couponURL = models.URLField()                                             # Special URL for coupon provided by vendor
    couponDescription = models.TextField()                                    # Coupon Description
    couponStore = models.ForeignKey(stores)                                   # Key of coupon to store    
    failure = models.IntegerField(default=0)                                  # Count of the number of times this has failed
    success = models.IntegerField(default=1)                                  # Count of the number of times people have made it work
    active =  models.BooleanField(default=True)                               # Coupon status active or not
    couponCode = models.CharField(max_length=30)                              # Coupon code
    couponValue = models.CharField(max_length=50)                             # Coupon value in Rs.
    featured =  models.BooleanField(default=False)                            # Coupon status featured or not 
    updatedAt = models.DateTimeField(auto_now=True)                           # Date on which coupon updated on 
    lastTested = models.DateTimeField(auto_now=True)                          # When was the coupon last tested
    addedOn = models.DateTimeField(auto_now_add=True)                         # Date on which coupon added on   
    createdAt = models.DateTimeField(auto_now_add=True)                       # Date on which coupon is created 
    couponTitle = models.CharField(max_length=100,default="")                 # Coupon Title

    def getCouponStoreName(self):
        """Method to return store name related to coupons"""
        return self.couponStore.storeName    

    def storeHash(self):
        """Method to return store hash related to coupon for mypromocodes.in"""
        return self.couponStore.hash

    def couponStoreURL(self):
        """Method to return store Hash related to coupon for mypromocodes.in"""
        return self.couponStore.seo_url + _storeURL + self.couponStore.hash

    def convertLastTestedToDate(self):
        """Method to return convert lastTestedDtae format"""
        return self.lastTested.strftime('%B %d %Y')

    def storeImage(self):
        """Method to return store Image related to coupon"""
        return self.couponStore.imageURL()

    def couponVote(self):
        """This method returns coupons success %"""
        returnVariable = int(float(self.success)/float(self.failure+self.success)*100)
        return returnVariable

    def commentCount(self):
        """Method to return Comment count related to count"""
        for t in coupons.objects.filter(couponTitle=self.couponTitle):
            count = ",".join([str(a.id) for a in t.comments_set.all()])
            count = count.split(',')
            count = filter(None,count)
            return len(count)

    def couponCommentData(self):
        """This method returns comment data related to coupon"""
        temp = []
        for i in coupons.objects.filter(id=self.id):
            for y in i.comments_set.all():
                dataDict = {'comment':y.comment,'addedOn':y.addedOn,'userName':y.userName}
                temp.append(dataDict)
        if temp:
            returnVariable = sorted(temp, key=lambda k: k['addedOn'],reverse=False)
        else:
            returnVariable = []
        return returnVariable

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

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

我在标签模型中有couponsId方法可用于根据标签的数量对标签进行排序。请帮帮我。

1 个答案:

答案 0 :(得分:5)

你走了:

from django.db.models import Count

sorted = coupons.objects.all()\
         .annotate(tags_count=Count('couponStore__storeTags')\
         .order_by('-tags_count')

没有什么是个人的,但你真的必须阅读这两个: