我有这样的事情:
class Basket(models.Model):
owner = models.ForeignKey(User, related_name='user_basket', verbose_name='Owner')
name = models.CharField("Basket_Name", max_length=30)
products = models.ManyToManyField('Product', through='BasketProduct', blank=True, null=True)
class BasketProduct(models.Model):
product = models.ForeignKey('Product')
basket = models.ForeignKey('Basket')
quantity = models.IntegerField()
我尝试从用户Basket
获取所有产品,并以“Notebook - 2,PC - 5,Phone - 1”的形式创建其价格和名称字符串
我的尝试:
user = request.user
b = Basket.objects.filter(owner=user)
bp = BasketProduct.objects.filter(basket=b)
for a in bp:
a = '%s - %s' % (a.product, a.quantity)
print a
这在shell中返回类似的内容:
[06/Oct/2012 19:44:41] "GET /list/ HTTP/1.1" 200 0
PC - 3 #single object
Notebook - 1 #second single object
我需要:string =“PC - 3,Notebook - 1”
请帮忙
答案 0 :(得分:1)
你可以做你已经做过的前三个陈述。然后join通过循环查看前三个语句产生的查询集返回的中间结果数组:
', '.join(['%s - %s' % (a.product, a.quantity) for a in bp])