【问题标题】:backward many to many Django query向后多对多 Django 查询
【发布时间】:2013-04-10 12:31:36
【问题描述】:
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

我想找出与特定标签相关的所有商店。 for t in tags.objects.all(): print ([str(a.storeName) for a in t.stores_set.all()]) 通过使用上面的for循环,我可以获得与所有商店相关的所有标签......但实际上我正在使用Django rest-frameWork......现在我有一个使用序列化器返回相关商店名称的视图去商店...

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

但这不起作用...谁能帮帮我...

【问题讨论】:

  • 你的模型是stores,所以使用stores_set。您尝试使用store_set,可能这就是为什么您得到`'QuerySet' object has no attribute 'store_set'`
  • 始终以单数形式命名您的模型类,并且类名的首字母大写。
  • 当然,谢谢你的提示...

标签: python django django-rest-framework


【解决方案1】:

我找到了解决方案...

这是处理获取请求的类...

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

这是我的标签模型:

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"

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

【讨论】:

    【解决方案2】:

    很简单,用你的标签:

    tag.store_set.all()
    

    【讨论】:

      【解决方案3】:
      t = Tag.objects.get(pk=1)
      stores = t.stores_set.all()
      

      【讨论】:

      • 相关名称是一个字段,而不是一个模型。应该是storeTags_set
      • @karthikr 不应该是stores_set。请参阅 docs.djangoproject.com/en/dev/topics/db/examples/many_to_manyArticlePublication 示例。它的p2.article_set.all() 而不是p2.publication_set.all()
      • 你愿意帮助 OP 吗?
      猜你喜欢
      • 2019-05-18
      • 2022-01-18
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2022-01-23
      • 2014-03-28
      • 2011-08-03
      相关资源
      最近更新 更多