【问题标题】:returning json output from multiple table in django tastypie从 django sweetpie 中的多个表返回 json 输出
【发布时间】:2012-06-04 10:49:50
【问题描述】:

我已经用我的自定义字段扩展了django User,现在我需要从自定义表返回一个json输出以及username形成父表。

我在查询集中尝试了 select_related 但它没有返回 username

型号

class ExProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    cell_phone = models.CharField(max_length=200, blank=True)
    api_key=      models.CharField(max_length=200, blank=True)
    termination_date=models.DateField()
    picture=models.ImageField(upload_to='profile',blank=True)
    email=models.EmailField()
    homeAddress=models.CharField(max_length=200,blank=True)
    homeNumber=models.CharField(max_length=200,blank=True)

资源

class ProfileResource(ModelResource):

    class Meta:
         # the queryset below is working like ExProfile.objects.all() as it is not
         # returning username in json   
         queryset =ExProfile.objects.select_related('User').all()
         resource_name = 'entry'
         fields = ['username','api_key','email','homeAddress']   
         #authorization = Authorization()
         #authentication = MyAuthentication()
         filtering = {
             'api_key': ALL,
             'homeAddress': ALL,
             'email': ALL,
             'query': ['icontains',],
             }
         def apply_filters(self, request, applicable_filters):
                base_object_list = super(ProfileResource, self).apply_filters(request, applicable_filters)

                query  = request.META.get('HTTP_AUTHORIZATION')
                if query:
                    qset = (
                        Q(api_key=query)
                        )
                    base_object_list = base_object_list.filter(qset).distinct()

                return base_object_list

我的代码有什么遗漏吗?

【问题讨论】:

    标签: python django orm tastypie django-queryset


    【解决方案1】:

    这里不需要选择相关的。

    如果你只想要用户名而不是用户对象添加一个属性字段,你可以做正常的 Django __ 关系,例如

    class ProfileResource(ModelResource):
        uname = fields.CharField(attribute='user__username', readonly=True)
        class Meta:
            queryset =ExProfile.objects.all()
            ....
    

    【讨论】:

      猜你喜欢
      • 2013-06-22
      • 1970-01-01
      • 2013-07-11
      • 2011-10-24
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      相关资源
      最近更新 更多