Django的tastypie - 如何通过关系让多对多 [英] django-tastypie - How to make manytomany through relationship
问题描述
我工作的一个项目一个API和我有关系订单/产品通过这样的OrderProducts:
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
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 :)
推荐答案
现在的问题是这一行:
order = fields.ToOneField(OrderResource, 'order')
错误是pretty直线前进。 产品
真的没有命名的属性订单
。你的 OrderProduct
连接表呢,但你的M2M不会返回 OrderProduct
的IT返回产品
秒。
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 OrderProduct
s it returns Product
s.
这篇关于Django的tastypie - 如何通过关系让多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!