Django tastypie中多对多关系的嵌套资源。亲子关系

Django tastypie中多对多关系的嵌套资源。亲子关系,django,api,resources,nested,tastypie,Django,Api,Resources,Nested,Tastypie,我有两个资源,customer和Phone(我在这里通过只包含几个字段简化了它)。不同的客户可以拥有相同类型的手机。我编写了Modelresource类,并通过/customer/和/phone/访问API 现在我要做的是给某个客户打电话。so/客户/1/电话/ 这些就是我的课的样子 Models.py Api.py 类电话资源(ModelResource): 类元: queryset=Phone.objects.all() 允许的_方法=['get'] 资源名称='phone' 类Custom

我有两个资源,customer和Phone(我在这里通过只包含几个字段简化了它)。不同的客户可以拥有相同类型的手机。我编写了Modelresource类,并通过/customer/和/phone/访问API

现在我要做的是给某个客户打电话。so/客户/1/电话/

这些就是我的课的样子

Models.py Api.py
类电话资源(ModelResource):
类元:
queryset=Phone.objects.all()
允许的_方法=['get']
资源名称='phone'
类CustomerResource(模型资源):
电话=字段.ManyToManyField(电话资源,“电话”)
类元:
queryset=Customer.objects.all()
允许的_方法=['get','patch','put']
资源名称='客户'
身份验证=身份验证()
授权=授权()
def prepend_URL(自身):
返回[
url(r'^(?P%s)/(?P\w[\w/-]*)/电话%s$'%
(self.\u meta.resource\u name,尾随的\u斜杠()),
self.wrap_view('get_customer_phone')、name='customer_phone'),
]
def客户_电话(自助、请求、**kwargs):
#我的问题是这个函数是什么
#我只想获取给定客户的电话,不包括其他不属于他们的电话
我已经调查过了


但它不起作用。我一直把所有的电话都取回,而不仅仅是某个客户的电话。所以,如果John有android和ios,它应该同时返回这两个列表,但如果John有android,它应该只返回android。但这样做,我得到了所有的手机在手机模型

您确定需要单独的前置URL吗?您可以在许多字段参数中添加full=True以获得每个客户购买的电话列表:

class CustomerResource(ModelResource):
    phone = fields.ManyToManyField(PhoneResource, "phone", full=True)

    class Meta:
        queryset = Customer.objects.all()
        allowed_methods = ['get', 'patch', 'put']
        resource_name = 'customer'
        authentication = Authentication()
        authorization = Authorization()
型号:

class Phone(models.Model):
    phone_id= models.AutoField(primary_key=True)
    phone_type = models.CharField(max_length=100)


# Defines the Customer Model

class Customer(models.Model):
    customer_id= models.AutoField(primary_key=True)
    phones = models.ManyToManyField(Phone, related_name='customers')
Api:

类电话资源(ModelResource):
#TODO:更新路径
customers=fields.ManyToManyField('path.to.CustomerResource',“customers”)
类元:
queryset=Phone.objects.all()
允许的_方法=['get']
资源名称='phone'
类CustomerResource(模型资源):
电话=字段.ManyToManyField(电话资源,“电话”)
类元:
queryset=Customer.objects.all()
允许的_方法=['get','patch','put']
资源名称='客户'
身份验证=身份验证()
授权=授权()
def prepend_URL(自身):
返回[
url(r'^(?P%s)/(?P\w[\w/-]*)/电话%s$'%
(self.\u meta.resource\u name,尾随的\u斜杠()),
self.wrap_view('get_customer_phone')、name='customer_phone'),
]
def get_客户_电话(自我、请求、**kwargs):
尝试:
bundle=self.build_bundle(数据={'pk':kwargs['pk']},请求=请求)
obj=self.cached\u obj\u get(bundle=bundle,**self.remove\u api\u resource\u names(kwargs))
除ObjectDoesNotExist外:
返回HttpGone()
除了返回的多个对象外:
返回HttpMultipleChoices(“在此URI中找到多个资源”)
电话资源=电话资源()
返回电话资源。获取列表(请求,客户=obj.pk)

但这也将返回其他字段。我只想拿回电话。因此,如果客户有名字和姓氏,当我只需要他们的手机时,打电话返回所有字段是没有意义的。这就是为什么我想做一个嵌套的url/customer/1/phone/customer\u phone()。但问题是,我希望/customer以uri的形式返回电话资源,而/customer/1/phone/则返回full。但是我必须要么得到全部的,要么两个都得到URI。肯定有比这更好的解决方案……我尝试了一下,我不确定这是否可行。正如您所看到的,客户型号有电话,但电话型号没有客户。那么我怎样才能得到这个客户集关系呢。这是我想不出来的最大的事情!我唯一能做的就是在客户资源中使用phone=fields.ManyToManyField(PhoneResource,“phone”,related_name=“phone”)。这是否正确?Django自动添加了一个反向关系:Yea ok。我还是不能把客户的所有电话都拿回来。不断归还模型中的所有手机…我不确定该将什么放在customer_set的位置。通过查看我的模型和模型资源,有什么想法吗?有。现在可以了。尽管我不得不将路径作为字符串,因为我遇到了周期性的类导入错误。非常感谢你的帮助!!
class CustomerResource(ModelResource):
    phone = fields.ManyToManyField(PhoneResource, "phone", full=True)

    class Meta:
        queryset = Customer.objects.all()
        allowed_methods = ['get', 'patch', 'put']
        resource_name = 'customer'
        authentication = Authentication()
        authorization = Authorization()
class Phone(models.Model):
    phone_id= models.AutoField(primary_key=True)
    phone_type = models.CharField(max_length=100)


# Defines the Customer Model

class Customer(models.Model):
    customer_id= models.AutoField(primary_key=True)
    phones = models.ManyToManyField(Phone, related_name='customers')
class PhoneResource(ModelResource):
    # TODO: update path
    customers = fields.ManyToManyField('path.to.CustomerResource', "customers")

    class Meta:
        queryset = Phone.objects.all()
        allowed_methods = ['get']
        resource_name = 'phone'

class CustomerResource(ModelResource):
    phones = fields.ManyToManyField(PhoneResource, "phones")

    class Meta:
        queryset = Customer.objects.all()
        allowed_methods = ['get', 'patch', 'put']
        resource_name = 'customer'
        authentication = Authentication()
        authorization = Authorization()

    def prepend_urls(self):
        return [
            url(r'^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/phone%s$' %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_customer_phone'), name='customer_phone'),
        ]

    def get_customer_phone(self, request, **kwargs):
        try:
            bundle = self.build_bundle(data={'pk': kwargs['pk']}, request=request)
            obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices("More than one resource is found at this URI.")

        phone_resource = PhoneResource()
        return phone_resource.get_list(request, customers=obj.pk)