django-tastypie - How to make manytomany through relationship

我与影子孤独终老i 提交于 2019-12-22 04:43:29

问题


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:


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.



来源:https://stackoverflow.com/questions/9192503/django-tastypie-how-to-make-manytomany-through-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!