【发布时间】:2016-05-08 10:30:32
【问题描述】:
我有两个资源,客户和电话(我在这里只包含几个字段来简化操作)。不同的客户可以拥有相同类型的电话。我编写了我的 Modelresource 类并通过 /customer/ 和 /phone/ 访问 API
现在我想做的是为某个客户获取电话。所以 /customer/1/phone/
这些是我的课程的样子。
模型.py
# Defines the phone Model
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)
phone = models.ManyToManyField(Phone)
API.py
class PhoneResource(ModelResource):
class Meta:
queryset = Phone.objects.all()
allowed_methods = ['get']
resource_name = 'phone'
class CustomerResource(ModelResource):
phone = fields.ManyToManyField(PhoneResource, "phone")
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 customer_phone(self, request, **kwargs):
# My Question is what goes in this function
# I want to get only the phones for the given customer, and exclude other phones that does not belong to them
我已经调查过http://django-tastypie.readthedocs.org/en/latest/cookbook.html#nested-resources
但它不起作用。我不断拿回所有电话,而不仅仅是属于某个客户的电话。因此,如果 John 有一个 android 和一个 ios,它应该返回两个列表,但如果 John 有 android,它应该只返回 android。但是这样做我得到了电话模型中的所有电话。
【问题讨论】:
-
customer_phone()目前是什么样子的? -
让它工作的唯一方法是从客户资源中创建一个包,然后删除除电话字段之外的所有字段,然后将其返回。问题在于,我希望 /customer 将电话资源作为 uri 返回,而 /customer/1/phone/ 则返回完整。但我必须要么把两者都装满,要么都装满 uris。
-
肯定有比这更好的解决方案...
标签: django api resources nested tastypie