Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-tastypie - How to make manytomany through relationship

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

like image 793
djevg Avatar asked Feb 08 '12 11:02

djevg


1 Answers

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.

like image 59
Chris Pratt Avatar answered Nov 14 '22 10:11

Chris Pratt