I am trying to update the ids of a bunch of objects and a related table that refers to the objects.
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:
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.
It doesn't matter. pk is more independent from the actual primary key field i.e. you don't need to care whether the primary key field is called id or object_id or whatever. It also provides more consistency if you have models with different primary key fields.
What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.
In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects. In this article, we will see how it reduces the number of queries and make the program much faster.
The values_list() method allows you to return only the columns that you specify.
Implemented in 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. 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
From Django 1.8, you can use id
of ForeignKey object to update an object.
for fr,to in d.items():
Test.objects.filter(id=fr).update(id=to)
Question.objects.filter(test_id=fr).update(test_id=to)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With