问题
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 OrderProduct
s it returns Product
s.
来源:https://stackoverflow.com/questions/9192503/django-tastypie-how-to-make-manytomany-through-relationship