简体   繁体   中英

backward many to many Django query

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) # Time at which tag is created
    updatedAt = models.DateTimeField(auto_now=True)     # Time at which tag is updated

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(choices=PRIORITY_CHOICES,default=2)                # Store Popularity Number  
    storeImage = models.ImageField(upload_to="images")                                   # 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

I want to find out all the stores related to a particular tag. for t in tags.objects.all(): print ([str(a.storeName) for a in t.stores_set.all()]) By using above for loop i am able to get all the tags related to all the stores...But actually i am using Django rest-frameWork...Now i have a view which uses a serializer to return the names of the stores related to stores...

class tagList(generics.ListAPIView,APIView):

    serializer_class = getAllTagsDetailSerializer

    def get_queryset(self):
        key = self.request.QUERY_PARAMS.get('appKey', None)
        getTagName = self.request.QUERY_PARAMS.get('tagName', None)
        keyData = app.objects.filter(appKey=key).exists()    
        try:
            if keyData == True:

                return tags.objects.filter(tag=getTagName)
            else:
                raise exceptions.PermissionDenied
        except app.DoesNotExist:
            pass

`class getAllStoresDetailSerializer(serializers.ModelSerializer):
    storeImage = serializers.Field(source='imageURL')
    storeTags =serializers.Field(source='StoreTags')

    class Meta:
        model = stores
        fields = ('storeName','storeDescription','storeURL',
                    'storePopularityNumber','storeImage','storeTags',
                    'storeSlug','createdAt','updatedAt'
                 )`


class getAllTagsDetailSerializer(serializers.ModelSerializer):
    tagStores = RelatedField(Many=True)
    class Meta:
        model = tags
        fields = ('tagStores'                   
                    )

But this is not working...can anyone help me please ...

使用标签非常简单:

tag.store_set.all()
t = Tag.objects.get(pk=1)
stores = t.stores_set.all()

I found the solution ...

This the class which handles get request...

class tagList(generics.ListAPIView,APIView):
    model = tags
    serializer_class = getAllTagsDetailSerializer

    def get_queryset(self):
        key = self.request.QUERY_PARAMS.get('appKey', None)
        getTagName = self.request.QUERY_PARAMS.get('tagName', None)
        keyData = app.objects.filter(appKey=key).exists()    
        try:
            if keyData == True:
                return tags.objects.filter(tag=getTagName)
            else:
                raise exceptions.PermissionDenied
        except app.DoesNotExist:
            pass

This Serializer class:

class getAllTagsDetailSerializer(serializers.ModelSerializer):
    tagStores = serializers.Field(source='getAllStoreNames')

    class Meta:
        model = tags
        fields = ('tagStores')

And this is my tags model:

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) # Time at which tag is created
    updatedAt = models.DateTimeField(auto_now=True)     # Time at which tag is updated

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

    def getAllStoreNames(self):

        for t in tags.objects.filter(tag=self.tag):      
            return  ([str(a.storeName) for a in t.stores_set.all()])

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

Let me explain a bit if any one want to know... In my class tagList im setting a query set by return tags.objects.filter(tag=getTagName) Which will filter out all the names of stores based on the tagName specified ...Then it goes to serializer class where i am setting tagStores = serializers.Field(source='getAllStoreNames') Then it reads the fields values and call the getAllStoreNames which is inside the tags model which is returning the names of Store related tag... If anyone know much more efficient solution please do share...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM