Django 如何在一篇文章中创建模型资源和相关的多对多资源?

Django 如何在一篇文章中创建模型资源和相关的多对多资源?,django,api,tastypie,Django,Api,Tastypie,您好,我正在使用tastypie在项目上公开rest api,并且在如何实现资源的端点上遇到了难题,所以我的问题是: 我有以下几种型号 class Product(models.Model): # fields... class Order(models.Model): products = models.ManyToManyField('Product', through='OrderProduct') # other fields... class OrderPr

您好,我正在使用tastypie在项目上公开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
当我尝试使用以下请求数据发布到/orders/endpoint时

{
    "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应该与之相关的订单,我试图实现的是发布一个订单资源,其嵌套的OrderProduct数据是在同一post请求上创建的


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

谢谢你的回答,我确实缺少了顺序,但在我的情况下,必须是这样,此数据表示要创建的顺序以及填充中间表OrderProduct(json products字段)的相关数据,因此,我们的想法是向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(有点鸡蛋问题),因为订单尚未保存在数据库中,tastypie数据流将在ModelResource.obj_save方法上保存订单,该方法将调用ModelResource.save_m2m,该方法将在发生异常的地方创建OrderProduct寄存器

所以我需要知道我必须实现哪个tastypie钩子,以便在save_m2m尝试保存OrderProduct之前隐式设置该引用