0

您好我正在使用tastepie在一个项目中公开一个rest api,并且卡在如何实现资源的端点上,所以这是我的问题:

我有以下型号,

class Product(models.Model):
    # fields...

class Order(models.Model):
    products = models.ManyToManyField('Product', through='OrderProduct')
    # other fields...

class OrderProduct(models.Model):
    order      = models.ForeignKey('Order')
    product    = models.ForeignKey('Product')
    quantity   = models.IntegerField()
    unit_price = models.FloatField()

    class Meta:
        unique_together = ['order', 'product']

以及以下资源,

class ProductResource(ModelResource):
    class Meta:
        resource_name = 'products'
        queryset = Product.objects.all()
        allowed_methods = ['get']

class OrderResource(ModelResource):
    products = fields.ToManyField('agro.api.OrderProductResource', 'orderproduct_set', related_name='product', full=True)

    class Meta:
        resource_name = 'orders'
        queryset = Order.objects.all()
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get', 'put', 'delete']
        authentication = Authentication() # only for testing purposes
        authorization = Authorization() # only for testing purposes

    class OrderProductResource(ModelResource):
        product = fields.ForeignKey('agro.api.ProductResource', 'product')

        class Meta:
            resource_name = 'orderproducts'
            queryset = OrderProduct.objects.all()
            allowed_methods = ['get']
            include_resource_uri = False
            authentication = Authentication() # only for testing purposes
            authorization = Authorization()  # only for testing purposes

当我尝试使用以下请求数据 POST 到 /orders/ 端点时

{
    "products": [
        {
            "product": "/products/1/",
            "quantity": 4,
            "unit_price": 5
        }
    ]
}

我收到以下错误回溯

{
    "error_message": "orderproduct.order_id may not be NULL",
    "traceback": "Traceback (most recent call last):\n\n  File \"c:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 192, in wrapper\n    response = callback(request, *args, **kwargs)\n\n  File \"c:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 397, in dispatch_list\n    return self.dispatch('list', request, **kwargs)\n\n  File \"c:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 427, in dispatch\n    response = method(request, **kwargs)\n\n  File \"c:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 1165, in post_list\n    updated_bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))\n\n  File \"c:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 1784, in obj_create\n    self.save_m2m(m2m_bundle)\n\n  File \"c:\\Python27\\lib\\site-packages\\tastypie\\resources.py\", line 1951, in save_m2m\n    related_bundle.obj.save()\n\n  File \"c:\\Python27\\lib\\site-packages\\django\\db\\models\\base.py\", line 463, in save\n    self.save_base(using=using, force_insert=force_insert, force_update=force_update)\n\n  File \"c:\\Python27\\lib\\site-packages\\django\\db\\models\\base.py\", line 551, in save_base\n    result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)\n\n  File \"c:\\Python27\\lib\\site-packages\\django\\db\\models\\manager.py\", line 203, in _insert\n    return insert_query(self.model, objs, fields, **kwargs)\n\n  File \"c:\\Python27\\lib\\site-packages\\django\\db\\models\\query.py\", line 1593, in insert_query\n    return query.get_compiler(using=using).execute_sql(return_id)\n\n  File \"c:\\Python27\\lib\\site-packages\\django\\db\\models\\sql\\compiler.py\", line 912, in execute_sql\n    cursor.execute(sql, params)\n\n  File \"c:\\Python27\\lib\\site-packages\\django\\db\\backends\\util.py\", line 40, in execute\n    return self.cursor.execute(sql, params)\n\n  File \"c:\\Python27\\lib\\site-packages\\django\\db\\backends\\sqlite3\\base.py\", line 344, in execute\n    return Database.Cursor.execute(self, query, params)\n\nIntegrityError: orderproduct.order_id may not be NULL\n"
}

如您所见,我没有指定新的 OrderProduct 应该与之相关的 Order,我想要实现的是发布一个 Order 资源,它的嵌套 OrderProduct 数据是在同一个 POST 请求上创建的。

我的问题来了,我如何指定 OrderProduct 引用的订单应该是正在创建的当前订单,最惯用的方法是什么,覆盖水合物(不确定此时我是否有 django orm 订单对象实例,因此可能这样做)设置相关模型的顺序或重新实现 hydrate_m2m 甚至 save_m2m,关于如何做到这一点的任何建议?

4

1 回答 1

0

感谢您的回答,我确实缺少订单,但在我的情况下,它必须是这样的数据表示要创建的订单以及填充中间表 OrderProduct(json 产品字段)的相关数据,所以这个想法是api的用户在同一请求中传递有关订单的信息和相关数据,例如创建一个新订单,用户将使用以下数据发布

{
    "products": {
        "product": "/products/1",
        "quantity": 4,
        "unit_price": 5
    }
}

这些数据应生成以下数据库寄存器

Order
    # with and auto generated id

OrderProduct
    order # which points to the auto generated id
    product # points to a previous registered product

如果我通过订单字段,此时我没有任何有效的 id(有点像鸡蛋问题),因为订单尚未保存在数据库中,tastepie 数据流将把订单保存在 ModelResource.obj_save 方法和该方法将调用 ModelResource.save_m2m 来创建发生异常的 OrderProduct 寄存器。

所以我需要知道在 save_m2m 尝试保存 OrderProduct 之前我必须实现哪个美味的钩子才能隐式设置该引用。

于 2013-01-09T16:57:12.133 回答