1. 程式人生 > 其它 >Django 外來鍵欄位的更新和插入資料

Django 外來鍵欄位的更新和插入資料

參考資料:

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)