简体   繁体   English

在Django的ManyToManyField中显示多个实例

[英]Displaying multiple instances in a ManyToManyField in Django

Here's what I have in the image: 这是图像中的内容:

I would like to display what I colored in green. 我想显示我用绿色涂的颜色。 Basically I would like to display what each product cost. 基本上,我想显示每种产品的价格。 For Bob he cost $12010 and Jill cost $12010 for a total price of $24020. 对于Bob来说,他的价格为$ 12010,而Jill的价格为$ 12010,总价格为$ 24020。

Here's my code so far: 到目前为止,这是我的代码:

class PurchaseOrder(models.Model):
    product = models.ManyToManyField('Product', null =True)

    def get_products(self):
        return "<BR> </BR>".join([p.products for p in self.product.all()])
    get_products.allow_tags = True

class Product(models.Model):
    products = models.CharField(max_length=256, null =True)
    price_for_each_item = models.FloatField() #Here is what I want to be displayed as green

How can I do this? 我怎样才能做到这一点? Notice that each product gets a new line. 请注意,每个产品都有一个新行。 So I'm trying to get each indivdual item on the same line as that indivdual item's price. 因此,我试图将每个单独的商品都与该个人商品的价格放在同一行。 For example here is, 例如这里

Bob $12010.0 鲍勃(Bob)$ 12010.0

Jill $12010.0 吉尔$ 12010.0

You can use string concatenation to concatenate the name with the price. 您可以使用字符串串联将名称与价格串联。 If products should be the first part of the string and price_for_each_item the second part, use: 如果products应该是字符串的第一部分,而price_for_each_item是第二部分,请使用:

def get_products(self):
    return "<br />".join("%s %s" % (p.products, p.price_for_each_item) for p in self.product.all())

A few unrelated comments: 一些不相​​关的评论:
Note that, according to the XHTML standards (and recommended by the HTML standard), a tag without any real content, like the <br> tag should be self-closing (thus <br /> instead of <br> </br> ). 请注意,根据XHTML标准(并受HTML标准推荐),没有任何真实内容的标记(例如<br>标记)应该是自动关闭的(因此, <br />而不是<br> </br> )。

Also, removing the square brackets inside the join function will create a generator instead of a list. 另外,删除join函数内的方括号将创建一个生成器,而不是一个列表。 This will not create a (useless) intermediary list in memory and the process will be slightly faster. 这不会在内存中创建(无用的)中间列表,并且过程会稍快一些。 I think it's a good habit to develop in case you ever have to work with large lists where the reduced memory needs are substantial. 我认为这是一个良好的习惯,以防万一您不得不处理大量内存减少的大型列表。

And another note, null=True doesn't do anything on a ManyToManyField . 另外请注意, null=TrueManyToManyField上不做任何事情。 null=True removes the NOT NULL clause on the database-level, but m2m relations are saved in a separate table entirely. null=True删除数据库级别的NOT NULL子句,但是m2m关系完全保存在单独的表中。 If a model has no related models in a m2m relation, there are simply no records in the m2m table. 如果模型在m2m关系中没有相关模型,则m2m表中根本就没有记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM