【问题标题】:select_related() and many to many fields with ajax (Django)select_related() 和 ajax 的多对多字段(Django)
【发布时间】:2010-12-17 10:32:11
【问题描述】:

我有一个简单的观点,即我想同时响应 ajax 和常规 HTTP 请求。简化后如下所示:

def tag_search(request, tag):

    items = Item.objects.filter(tags__tagname__exact=tag)

    if request.is_ajax():

        return HttpResponse(serializers.serialize('json', items), mimetype='application/json')

    else:

        return render_to_response('mytemplate.html', locals())

问题在于它没有返回多对多关系的值 - 只是一个主键列表,例如:

[1, 2, 5]

我知道我不能使用 select_related() 来跟踪多对多关系 - 谁能为我提供传递该信息的最佳实践或示例?

【问题讨论】:

    标签: jquery ajax django json many-to-many


    【解决方案1】:

    更新 - 似乎 Django doesn't support this particularly well,但有一个第三方序列化程序可以:

    DjangoFullSerializers

    【讨论】:

      【解决方案2】:

      我已经写了some code 在我的项目中进行序列化。它基于上下文将模型对象序列化为字典,该上下文描述了如何序列化每种遇到的类型的对象,因此您可以从序列化中删除一些字段或添加模型中不存在的新字段。该代码缺少 cmets,但您可以在 unit tests 中找到使用示例。希望对您有所帮助。

      【讨论】:

      • 感谢您的发布 - 我会检查一下!
      【解决方案3】:

      您可能想做一个bulk select using those ids(可能是最简单的解决方案)

      item_ids = [1, 2, 5]
      Item.objects.in_bulk(item_ids)
      
      # Another option:
      Item.objects.filter(id__in=item_ids)
      

      编辑:我的建议是使用 django-tagging 为您处理此问题。或者只是在你的 Item 模型中添加一个方法来获取标签(并大量使用缓存)

      from django.core.cache import cache
      
      class Item(models.Model):
          ... 
      
          def get_tags(self):
              cache_key = "item_%s_tags" % self.id
              cache_timeout = 600  # 10 minutes or whatever
      
              tags = cache.get(cache_key, False)
              if not tags:
                  tags = self.tags.all()
                  cache.set(cache_key, tags, cache_timeout)
      
              return tags
      

      【讨论】:

      • 谢谢,这是一个有趣的想法,但我如何将相关对象“附加”到主对象以进行序列化?当我尝试使用除整数列表之外的任何内容重新定义 item.tags 时出现错误。
      猜你喜欢
      • 2012-01-15
      • 2011-06-26
      • 2019-04-19
      • 2013-04-27
      • 2011-10-16
      • 2011-02-05
      • 2020-10-28
      • 2014-06-28
      相关资源
      最近更新 更多