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)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM