python - 如何使用模型将筛选后的数据行从表移动到另一个表

标签 python django django-models bulkinsert

我有两个模型类 A 和 B,我想将一些行从表 A 移动到 B,我想知道如何正确执行此操作。

models.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=200)

class A(models.Model):
    title = models.CharField(max_length=200)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

class B(models.Model):
     title = models.CharField(max_length=200)
     category = models.ForeignKey(Category, on_delete=models.CASCADE)

views.py的代码

from models import A, B

def move(request):
    filtered_a = A.objects.filter(category=2)
    """
    Here I want to move filtered_a rows to B table,
    and how to deal with the id 
    """

拜托,我不是在谈论迁移,它是在点击操作之后进行的处理,欢迎任何干净、快速的方法来做到这一点。

提前谢谢您。

最佳答案

def move(request):
    filtered_a = A.objects.filter(category=2)
    filtered_b = [B(**a) for a in filtered_a]
    B.objects.bulk_create(filtered_b)

这应该可以解决问题。如果您的查询集很大,我建议在循环时使用迭代器。

[B(**a) for a in filtered_a.iterator()]

关于python - 如何使用模型将筛选后的数据行从表移动到另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54794145/

相关文章:

Python 使用 Fileinput 替换单词

python - Django 获取客户端的域名/主机名

python - 在 Angular 4 模板中使用 django 标签?

django - 按外键/相关字段对 django 查询集进行分组

django - 如何检查 Django 中是否存在模型名称?

Django 列 wagtailcore_page.draft_title 不存在

python - 获取日期作为数组

python - 需要 Scrapy 登录 vBulletin 指导

django - 如何在 django 模型中存储元组列表

python - 在 Windows 中为 OpenERP 6.1 安装 Python 模块