django-tastypie - 如何通过关系实现多对多
我正在为一个项目开发一个 API,并且通过 OrderProducts 有一个关系 Order/Products,如下所示:
在 Catalog/models.py 中
class Product(models.Model):
...
在 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):
In order/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'
这给了我这个错误消息:“'Product'对象没有属性'order'”。所以我不确定有什么问题或缺失,它可能也需要我的产品资源中的某些内容,但我尝试了几种方法但没有成功。欢迎任何帮助:)
I'm working on a API for a project and I have a relationship Order/Products through OrderProducts like this:
In catalog/models.py
class Product(models.Model):
...
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)
...
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):
In order/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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在这一行:
错误非常简单。
Product
实际上没有名为order
的属性。您的OrderProduct
连接表确实如此,但您的 M2M 不会返回OrderProduct
,而是返回Product
。The problem is with this line:
The error is pretty straight-forward.
Product
really doesn't have an attribute namedorder
. YourOrderProduct
join table does, but your M2M doesn't returnOrderProduct
s it returnsProduct
s.