我的Django应用程序中有以下模型:订单与购物车相关, cartItem 与购物车和产品。现在我的tastypie api当我获得订单时,我也希望获得与订单购物车相关的所有产品。
class Order(models.Model):
objects = OrderManager()
order_number = models.CharField(max_length=20, editable=False,unique=True,
default=get_unique_order_number)
user = models.ForeignKey(User, blank=True, null=True)
cart = models.ForeignKey(Cart, blank=True, null=True)
...
class Cart(models.Model):
user = models.ForeignKey(User)
is_check_out = models.BooleanField(default=False)
...
class CartItem(models.Model):
objects = CartItemManager()
cart = models.ForeignKey(Cart)
product = models.ForeignKey(Product)
...
class CartRelatedResource(ModelResource):
class Meta:
queryset = Cart.objects.all()
allowed_methods = ['get']
excludes = ['is_check_out', 'session', 'creation_date', 'modification_date']
include_resource_uri = False
authentication = SessionAuthentication()
class OrderResource(ModelResource):
cart = fields.ForeignKey(CartRelatedResource, 'cart',full=True)
class Meta:
queryset = Order.objects.all()
resource_name = 'order'
fields = ['cart_id','delivery_time','shipping_address_id','billing_address_id',
'tip','phone','delivery_instructions']
include_resource_uri = False
allowed_methods = ['post','get']
authentication = SessionAuthentication()
authorization = OrderAuthorization()
我不认为在这种情况下使用ToManyField会起作用。会吗?实现我想要的最好方法是什么?
答案 0 :(得分:0)
我想我已经解决了。如您所知,products
字段是最重要的部分:
class ProductRelatedResource(ModelResource):
class Meta:
queryset = Product.objects.all()
fields = ['id', 'name']
include_resource_uri = False
class OrderResource(ModelResource):
products = fields.ToManyField(ProductRelatedResource,
attribute=lambda bundle: Product.objects.filter(cartitem__cart=bundle.obj.cart), full=True)
class Meta:
queryset = Order.objects.all()
resource_name = 'order'
include_resource_uri = False