简体   繁体   English

Django更新queryset以更改ForeignKey的ID

[英]Django update on queryset to change ID of ForeignKey

I am trying to update the ids of a bunch of objects and a related table that refers to the objects. 我试图更新一堆对象的id和引用对象的相关表。

class Test(models.Model):
    id=models.IntegerField(primary_key=True)

class Question(models.Model):
    id=models.AutoField(primary_key=True)
    test=models.ForeignKey('Test',db_column='testId')


d={1:2,5:10}

for fr,to in d.items():
    Test.objects.filter(id=fr).update(id=to)
    Question.objects.filter(test_id=fr).update(test_id=to)

I have tried test_id , test__id and testId but get this error message: 我已经尝试过test_idtest__idtestId但是收到此错误消息:

django.db.models.fields.FieldDoesNotExist: Question has no field named 'test_id'

Is this currently possible? 这目前可能吗?

Edit: I would prefer not to have to load the Test object for each id change. 编辑:我宁愿不必为每个id更改加载Test对象。

Implemented in Django 1.8 在Django 1.8中实现

Usage: 用法:

Bar.objects.filter(pk=foo.id).update(a_id=bar.id)
Bar.objects.filter(pk=foo.id).update(a=bar.id)

See ticket and commit . 查看故障单提交

You cannot update ForeignKey field with ID. 您无法使用ID更新ForeignKey字段。 You should pass the model object to update it. 您应该传递模型对象来更新它。 You can try 你可以试试

for fr,to in d.items():
    Test.objects.filter(id=fr).update(id=to)
    test_obj = Test.objects.get(id=to)
    Question.objects.filter(test_id=fr).update(test=test_obj)

Refer Documentation 参考文档

Update: 更新:

From Django 1.8, you can use id of ForeignKey object to update an object. 从Django 1.8开始,您可以使用ForeignKey对象的id来更新对象。

for fr,to in d.items():
    Test.objects.filter(id=fr).update(id=to)
    Question.objects.filter(test_id=fr).update(test_id=to)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM