用关系在django-rest-framework中创建一个rest api

时间:2017-03-30 05:09:56

标签: django-rest-framework

在django-rest-framework

中创建一个rest api

我有2张桌子

拳头表:用户

id   | PK
Name | varchar(255)

第二张表:地址

id      | PK
address | varchar(255)
city_id | int
user_id | FK

现在,当我点击用户查询时,我也想要用Json格式的用户地址

喜欢这个

[
  {
    "id": 98,
    "name": "rijoj@selectsourceintl.com",

    "address": [
      {
        "id": 51,
        "city_id": 5,
        "addrss": "New York",
      },
      {
        "id": 61,
        "city_id": 5,
        "addrss": "California",
      },
    ]
  }
]

1 个答案:

答案 0 :(得分:3)

models.py -

class User(models.Model):
    catcher_fname = models.CharField(max_length = 128, blank = True)
    catcher_lname = models.CharField(max_length = 128, blank = True)
    api_key = models.CharField(max_length = 100, blank = False)



class Address (models.Model):
    address = models.CharField(max_length = 150)
    city = models.CharField(max_length = 255)
    user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='addresses')

注意 - id字段是在django中自动增量和内置的,您不需要直接指定它。 以下是演示如何链接用户obj和地址obj。

>> from .models import User,Address
>> user_obj = User.objects.get(pk=pk)
>> address_obj = Address.objects.get(pk=address_pk)
>> user_obj.address = address_obj
>> user_obj.save()

稍后您可以从用户对象访问地址 -

>> from .models import User
>> user_obj = User.objects.get(pk=pk)
>> user_obj.addresses.all() (will give the data)

现在安装django-restframework

views.py -

from rest_framework.generics import RetrieveAPIView
from .serializers import UserDetailSerializer


class UserAPIView(RetrieveAPIView):
      serializer_class = UserDetailSerializer
      lookup_field = 'id'
      queryset = User.objects.all()

serializers.py -

from .models import User,Address
from rest_framework import serializers


class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ('id', 'city_id', 'address')

class UserDetailSerializer(serializers.ModelSerializer):
    address = AddressSerializer(many=True)
    class Meta:
           model = User
           fields = (
              'id',
              'name',
              'address'
           )

<强> urls.py

from django.conf.urls import url

from reports.views import UserAPIView

urlpatterns = [
    url(r'^users/(?P<id>[0-9]+)/$',UserAPIView.as_view(), name= 'users'),
]