我有以下型号:
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)
cart = models.ForeignKey(Cart)
class OrderItem(models.Model):
objects = OrderItemManager()
order = models.ForeignKey(Order, related_name="items")
product = models.ForeignKey(Product)
quantity = models.PositiveSmallIntegerField()
price = models.DecimalField(max_digits=6, decimal_places=2, default=0.00)
tax = models.DecimalField(max_digits=6, decimal_places=2, default=0.00)
ITEM_STATUS = (
('PENDING', 'Pending'),
('REFUND', 'Refund'),
('CANCEL', 'Cancel'),
)
status = models.CharField(max_length=10, choices=ITEM_STATUS,
default="PENDING")
class Cart(models.Model):
user = models.ForeignKey(User)
creation_date = models.DateTimeField(auto_now_add=True)
modification_date = models.DateTimeField(auto_now=True, auto_now_add=True)
is_check_out = models.BooleanField(default=False)
可以有多个订单使用相同的购物车。 每个订单都有多个订单商品。 我想在同一个购物车中获取状态='退款'的所有OrderItems。 我怎么能得到它?
Additonal Info:我正在使用美味馅饼进行api通话
class RefundItemAuthorization(Authorization):
def read_list(self, object_list, bundle):
print 'Read List RefundItemAuthorization'
if bundle.request.user.is_admin:
return object_list.all()
else:
raise Unauthorized("Only admin user can access this.")
class OrderItemRefundResource(ModelResource):
product = fields.ForeignKey('store.api.ProductResource', 'product', full=True)
class Meta:
queryset = OrderItem.objects.filter(status='REFUND')
resource_name = 'item_refund'
include_resource_uri = False
allowed_methods = ['get']
limit = 0
authentication = SessionAuthentication()
authorization = RefundItemAuthorization()
示例:
{
"cart": [
{
"id": 1,
"orderitem": [
{
"id": 22,
"product": {
"brand_name": "A",
"cost_price": "0.69",
"description": "XXXX"
}
},
{
"id": 33,
"product": {
"brand_name": "B",
"cost_price": "0.50",
"description": "XXXXX"
}
}
]
}
]
}
答案 0 :(得分:0)
一个选项:
import defaultdict from collections
d = defaultdict(list)
for item in OrderItem.objects.filter(status='REFUND'):
d[item.order.cart.id].append(item)
print(d)
# d is a dict from cart id to a list of OrderItems
(或者如果你精通iterables,你可以使用itertools.groupby
。)