[英]How to save the data that has same model but with different data in Django
I'm working on a mini project which uses Django 1.8. 我正在使用Django 1.8的小型项目中工作。 The aim is to build a small billing app. 目的是构建一个小型计费应用程序。 So, I've created two models, Bill and Product, as follows. 因此,我创建了两个模型,即Bill和Product,如下所示。
#bill/models.py
class Bill(models.Model):
date_of_issue = models.DateField()
name = models.CharField(max_length=50, default="N/A", null=True)
address = models.CharField(max_length=150, default="N/A", null=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
return "{} {}".format(self.input_name, self.date_of_issue)
class Product(models.Model):
bill = models.ForeignKey(Bill, on_delete=models.CASCADE)
description = models.CharField(max_length=100, default="N/A")
quantity = models.IntegerField(default=0)
total = models.IntegerField(default=0)
By seeing the model, you can tell that my approach is to create Bill and Product tables and connect the Product to Bill via ForeignKey. 通过查看模型,您可以知道我的方法是创建Bill和Product表,并通过ForeignKey将Product连接到Bill。 Now, the thing is that a single bill will contain at least one product. 现在,问题是一张帐单将至少包含一种产品。 If there are more than one product, how should I write my views in views.py . 如果产品不止一种,我应该如何在views.py中编写我的观点。 I'm a beginner in the Django development. 我是Django开发的新手。 If a Bill contains a single Product then I can write its view. 如果法案包含单个产品,那么我可以写出它的观点。 But how can I store multiple Product which have different data and storing it in database. 但是,如何存储具有不同数据的多个产品并将其存储在数据库中。
For Example 例如
The user will enter the name and address of the customer. 用户将输入客户的姓名和地址。 Then the user will enter the details of products. 然后,用户将输入产品的详细信息。 Now I want to generate the Product modelform more than once (depends upon the number of products added by user). 现在,我想多次生成Product模型表单(取决于用户添加的产品数量)。 How can I accomplish this ? 我怎样才能做到这一点?
Assuming 假设
1) multiple products can be bought at once (and thus be part of one bill) and 1)可以一次购买多种产品(因此成为一张账单的一部分),并且
2) one product can be bought multiple at any time (and thus be part of many bills) 2)可以随时购买多种产品(因此可以成为许多票据的一部分)
a simple foreign key is the wrong modelling attempt. 一个简单的外键是错误的建模尝试。 Instead of a m:1 relation you need a m:n relation - and thus a ManyToManyField . 代替m:1关系,您需要一个m:n关系-因此需要ManyToManyField 。 With a ManyToManyField you can add multiple products to one bill or have mutiple products added to multiple bills. 使用ManyToManyField,您可以将多个产品添加到一个帐单中,也可以将多个产品添加到多个帐单中。 In django-admin it's useful (and I recommend it) to put ManyToManyFields as filter_horizontal
which eases the use of this field. 在django-admin中,将ManyToManyFields设置为filter_horizontal
很有用(我建议这样做),这可以简化该字段的使用。
Plus, django will automatically resolve your m:n relation with an additional third database table, so you don't need to take care of this. 另外,django会自动使用附加的第三个数据库表来解决您的m:n关系,因此您无需进行任何处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.