我有两个模型类 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/