tastypie 多表关系

来源:互联网 发布:淘宝会员怎么取消 编辑:程序博客网 时间:2024/06/06 17:50

看了论坛上这篇文章,帮我解决了tastypie 多表关系通过外键查询相关联的数据库,

前置条件:

安装tastytie包:

sudo pip install django-tasypie

在django工程里面配置tastypie相关信息:

在主urls.py里面做如下配置把url和resource建立映射关系:

from tastypie.api import Apifrom my_app.api.resources import MyModelResourcev1_api = Api(api_name='v1')v1_api.register(CustomerResource())v1_api.register(AddressInfoResource())v1_api.register(BasicInfoResource())urlpatterns = patterns('',  # ...more URLconf bits here...  # Then add:  (r'^api/', include(v1_api.urls)),)

三个数据模型如下:

class Customer(models.Model):    id = models.IntegerField(primary_key=True)    joining_dtm = models.DateTimeField()    isactive = models.IntegerField()    class Meta:        db_table = u'Customer'class Addressinfo(models.Model):    id = models.IntegerField(primary_key=True)    apt_num = models.CharField(max_length=135, blank=True)    street = models.CharField(max_length=135, blank=True)    street_2 = models.CharField(max_length=135, blank=True)    city = models.CharField(max_length=135, blank=True)    country = models.CharField(max_length=135, blank=True)    postalcode = models.CharField(max_length=135, blank=True)    customer_id = models.ForeignKey(Customer)    class Meta:        db_table = u'AddressInfo'class Basicinfo(models.Model):    id = models.IntegerField(primary_key=True)    name = models.CharField(max_length=135, blank=True)    about = models.CharField(max_length=135, blank=True)    website = models.CharField(max_length=135, blank=True)    customer_id = models.ForeignKey(Customer)    class Meta:        db_table = u'BasicInfo'

tastypie api.py的ModelResourcer内容如下:

from tastypie.resources import ModelResourcefrom user_blog.models import Basicinfo,Addressinfo,Customerfrom tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS

class CustomerResource(ModelResource):    # The 2nd parameter is tricky:    # Try suffixing with nothing, 's', or '_set'    # e.g. 'addressinfo', 'addressinfos', 'addressinfo_set'    addressinfos = fields.ToManyField('your_app_name.api.AddressInfoResource', 'addressinfo_set', Full=True)    basicinfos = fields.ToManyField('your_app_name.api.BasicInfoResource', 'basicinfo_set', Full=True)    class Meta:        queryset = Customer.objects.all()        resource_name = 'customer'class AddressInfoResource(ModelResource):    class Meta:        queryset = Addressinfo.objects.all()        resource_name = 'addressinfo'class BasicInfoResource(ModelResource):    class Meta:        queryset = Basicinfo.objects.all()        resource_name = 'basicinfo'


开启服务,在地址栏中输入:

127.0.0.1:8000/api/v0.1a/customer/?format=json
就可以得到与Customer外键相关联AddressInfo和BasicInfo表的json格式的信息



0 0