Python 向后多对多Django查询

Python 向后多对多Django查询,python,django,django-rest-framework,Python,Django,Django Rest Framework,我想找出与特定标签相关的所有商店。 用于标记.objects.all()中的t: 打印([str(a.storeName)用于t.stores\u set.all()]) 通过使用上面的for循环,我能够获得与所有存储相关的所有标记…但实际上我使用的是Django rest框架…现在我有了一个视图,它使用序列化程序返回与存储相关的存储的名称 class tags(models.Model): """ This is the tag model """ tag = models.C

我想找出与特定标签相关的所有商店。
用于标记.objects.all()中的t:
打印([str(a.storeName)用于t.stores\u set.all()])
通过使用上面的for循环,我能够获得与所有存储相关的所有标记…但实际上我使用的是Django rest框架…现在我有了一个视图,它使用序列化程序返回与存储相关的存储的名称

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

但这不起作用…有人能帮我吗…

很简单,有你的标签:

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'                   
                    )

我找到了解决办法

这是处理get请求的类

t = Tag.objects.get(pk=1)
stores = t.stores_set.all()
此序列化程序类:

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
这是我的标签模型:

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

    class Meta:
        model = tags
        fields = ('tagStores')
让我解释一下如果有人想知道。。。
在我的类标记列表中,我设置了一个由return
tags.objects.filter(tag=getTagName)
设置的查询集,该查询集将根据指定的标记名过滤掉所有存储的名称…然后它转到序列化器类,我在其中设置
tagStores=serializers.Field(source='getAllStoreNames')
然后读取字段值并调用标签模型中的
getAllStoreNames
,该模型返回与商店相关的标签的名称。。。如果有人知道更有效的解决方案,请分享

相关名称与字段相关,而不是与模型相关。它应该是
storeTags\u set
@karthikr不应该是
stores\u set
。参见和
文章
出版物
示例。它的
p2.article\u set.all()
和not
p2.publication\u set.all()。您尝试了使用
store\u set
,这可能就是为什么您得到了“QuerySet”对象没有属性“store\u set”`总是用单数命名模型类,并用大写字母命名类名。当然,谢谢您的提示。。。
class getAllTagsDetailSerializer(serializers.ModelSerializer):
    tagStores = serializers.Field(source='getAllStoreNames')

    class Meta:
        model = tags
        fields = ('tagStores')
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"