Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 311
Adam Kerz Avatar asked Jan 19 '15 07:01

Adam Kerz


People also ask

Is PK and ID same in Django?

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 does ForeignKey mean in Django?

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.

What does Select_related do in Django?

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.

What does .values do in Django?

The values_list() method allows you to return only the columns that you specify.


2 Answers

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.

like image 162
laffuste Avatar answered Sep 30 '22 07:09

laffuste


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

Update:

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)
like image 35
arulmr Avatar answered Sep 30 '22 07:09

arulmr