參考資料:
https://www.cnblogs.com/zhukaijian/p/11561128.html
https://blog.csdn.net/lmw1239225096/article/details/78397847
model表
### 文件model class FileProperty(models.Model): filename = models.CharField(max_length=250, verbose_name='文件名稱') productline = models.ForeignKey(ProductLine, verbose_name='產品線' ,null=True ,on_delete=models.SET_NULL) upload_time = models.DateTimeField(auto_now_add=True, verbose_name='上傳時間') describe = models.CharField(max_length=1000, verbose_name='備注') ##產品線 class ProductLine(models.Model): name = models.CharField(verbose_name='產品線名稱', max_length=250, unique=True)
需要向 FileProperty 表中插入一條數據,views.py 如下:
productline = request.POST.get('productline').strip() file_list = { 'filename': file.name, 'productline': productline 'describe': request.POST.get('describe', ''), } FileProperty.objects.create(**file_list)
當執行時報錯如下:
FileProperty 字段 productline 為 ForeignKey(一對多) 解決方法:
productline_object = ProductLine.objects.get(name=productline) FileProperty.objects.create(**file_list, productline=productline_object)
FileProperty 字段 productline 為 ManyToManyField(多對多)時的解決方法:
productline_object = ProductLine.objects.get(name=productline) fileadd = FileProperty.objects.create(**file_list) fileadd.productline.add(productline_object)