django-tastypie - How to make manytomany through r

2019-04-27 02:53发布

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 :)

1条回答
女痞
2楼-- · 2019-04-27 03:40

The problem is with this line:

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

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.

查看更多
登录 后发表回答