django-tastypie - 如何通过关系使许多人 [英] django-tastypie - How to make manytomany through relationship

查看:36
本文介绍了django-tastypie - 如何通过关系使许多人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个项目开发 API,我通过 OrderProducts 建立了 Order/Products 关系,如下所示:

I'm working on a API for a project and I have a relationship Order/Products through OrderProducts like this:

在目录/models.py

In catalog/models.py

class Product(models.Model):
    ...

按顺序/models.py

In order/models.py

class Order(models.Model):
    products = models.ManyToManyField(Product, verbose_name='Products', through='OrderProducts')
    ...

class OrderProducts(models.Model):
    order = models.ForeignKey(Order)
    product = models.ForeignKey(Product)
    ...

现在,当我通过 API 加载订单时,我也想获取相关产品,所以我尝试了这个(使用 django-tastypie):

Now, when I load an Order through the API I'd like to get the related Products as well, so I tried this (with django-tastypie):

按顺序/api.py

class OrderResource(ModelResource):
    products = fields.ToManyField('order.api.OrderProductsResource', products, full=True)

    class Meta:
        queryset = Order.objects.all()
        resource_name = 'order'

class OrderProductsRessource(ModelResource):
    order = fields.ToOneField(OrderResource, 'order')

    class Meta:
        queryset = OrderProducts.objects.all()
        resource_name = 'order/products'

这给了我这个错误消息:‘产品’对象没有属性‘订单’".所以我不确定出了什么问题或遗漏了什么,它可能也需要我的产品资源中的一些东西,但我尝试了几种方法都没有成功.欢迎任何帮助:)

which give me this error message: "'Product' object has no attribute 'order'". So I'm not sure what's wrong or missing, it probably requires something in my Product resource as well but I tried several way without success. Any help would be welcome :)

推荐答案

问题出在这一行:

order = fields.ToOneField(OrderResource, 'order')

这个错误很直接.Product 确实没有名为 order 的属性.您的 OrderProduct 连接表可以,但您的 M2M 不返回 OrderProducts,而是返回 Products.

The error is pretty straight-forward. Product really doesn't have an attribute named order. Your OrderProduct join table does, but your M2M doesn't return OrderProducts it returns Products.

这篇关于django-tastypie - 如何通过关系使许多人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆