django rest框架 - 使用单个API调用创建具有外键的资源

时间:2015-03-18 02:55:46

标签: django api rest

我无法创建“估算”资源。基本上,我想要实现的是创建一个单独的API调用来创建一个“Estimate”实例,该实例有3个外键,并且更喜欢使用ModelViewSet来利用它所带来的所有方法(POST, GET,PUT,DELETE,PATCH)。

示例:

使用以下数据进行单个POST调用: {user:,property:,estimate_type:,message:“test message”} / API /估计/

我设法配置API以检索我需要的所有细节,但“用户”对象详细信息除外,而我只获取URL,但我想这没关系,因为我可以获取用户详细信息单独的电话。

我有点困惑,并且想要了解通过一次调用实现创建“Estimate”实例的正确方法是什么。我应该覆盖“估计”类的保存方法吗?

非常感谢所有建议。

的Django == 1.7.6 djangorestframework == 3.1.0

这些是我的模特:

class Property(models.Model):
    user         = models.ForeignKey(User)
    address      = models.CharField(max_length=100)

def __str__(self):
    return self.address


class EstimateType(models.Model):
    name          = models.CharField(max_length=100)

def __str__(self):
    return self.name

class Estimate(models.Model):
    user          = models.ForeignKey(User)
    property      = models.ForeignKey(Property)
    estimate_type = models.ForeignKey(EstimateType)
    message       = models.TextField(max_length=144)

def __str__(self):
    return "{} {}".format(self.user.username, self.property.address1)

这些是序列化器:

class UserSerializer(serializers.HyperlinkedModelSerializer):

class Meta:
    model = User
    fields = ('pk','username', 'email','first_name', 'last_name', 'is_staff')

class PropertySerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = Property
        fields = ('pk','address','user')

class EstimateTypeSerializer(serializers.ModelSerializer):

    class Meta:
        model = EstimateType
        fields = ('pk', 'name')

class EstimateSerializer(serializers.HyperlinkedModelSerializer):
    property = PropertySerializer()
    service  = EstimateTypeSerializer()

class Meta:
    model = Estimate
    fields = ('pk','user','property','service', 'message')

ViewSets:

class UserViewSet(viewsets.ModelViewSet):
    queryset         = User.objects.all()
    serializer_class = UserSerializer

class PropertyViewSet(viewsets.ModelViewSet):
    queryset         = Property.objects.all()
    serializer_class = PropertySerializer

class EstimateTypeViewSet(viewsets.ModelViewSet):
    queryset         = EstimateType.objects.all()
    serializer_class = EstimateTypeSerializer

class EstimateViewSet(viewsets.ModelViewSet):

    serializer_class = EstimateSerializer

    def get_queryset(self):
        queryset = Estimate.objects.filter(user=self.request.user)
        return queryset

发送GET请求 / API /估计/

检索以下内容:

    [
  {
    "pk": 3,
    "user": "http://localhost:8000/users/2/",
    "property": {
      "pk": 3,
      "address": “123 Fake street",
      "user": {
        "pk": 2,
        "username": “admin”,
        "email": “admin@foo.com”,
        "first_name": “Foo”,
        "last_name": “Bar”,
        "is_staff": true
      }
    },
    “estimate_type”: {
      "pk": 1,
      "name": “basic”
    },
    "message": "Lorem Ipsum is simply dummy text of the printing and typesetting \n”
  }
]

1 个答案:

答案 0 :(得分:1)

要创建链接到其他现有记录的新Estimate,您只需要发送这样的对象,只需要识别相关对象的主键:

{
    "user": <user pk>,
    "property": <property pk>,
    "estimate_type": <estimate type pk>,
    "message": "foo bar"
}

restframework 2.x不支持写入嵌套的序列化程序 - 正如您所做的那样。

了解如何创建可写的RelatedField类:http://www.django-rest-framework.org/api-guide/relations/#custom-relational-fields