Reputation: 115
I have below django model (with managed=False).
class MyModel(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=250)
description = models.TextField()
client = models.ForeignKey(Client)
created_on = models.DateTimeField(null=True, blank=True)
user = models.ForeignKey(User, related_name='user')
last_modified_by = models.ForeignKey(User, related_name='last_modified_by', null=True)
last_modified_on = models.DateTimeField(null=True, blank=True)
class Meta:
managed = False
when I execute 'python manage.py shell' and type in below two statements, I could see the row added in the mysql db.
>>> dm = MyModel(name='name1', description='test1', client_id=6,user_id=9,last_modified_by_id=9)
>>> dm.save()
But when I run the server 'python manage.py runserver' and execute the same statement in a class method, the save() goes through but there is no new row added in the DB.
def funcname(self, request):
print("Creating new row...")
self.var = MyModel(name='testName',description='testDescription',client_id=6, user=9, last_modified_by=9)
self.var.save()
print("Created new row')
Observations:
The two print statements do get printed on the console. But no entry in the db.
No error/exception in the funcname().
Tried with giving unique entries for diff columns. Same result
When ran the server with pdb.set_trace() at the beginning of the function, it was found the MyModel.objects.filter() gives right number of rows. But this number does not match when looked in the db.
(Pdb) MyModel.objects.filter()
shows list of 2 MyModel objects.
But when checked by logging into DB, the corresponding table has only 1 row.
Using Python 2.7
Any pointers on what may be going on ?
Thanks in advance!
Upvotes: 1
Views: 394
Reputation: 115
After digging a bit more, I found that somewhere in the caller, transaction.atomic decorator was used. This was causing the write to db table to fail. I am updating this here hoping that this will help someone in future.
Thanks to all who replied.
Cheers!
Upvotes: 1
Reputation: 1612
You can just do the following
def funcname(self, request):
self.var = MyModel.objects.create(name='testName',description='testDescription',client_id=6, user=9, last_modified_by=9)
And Daniel commented about the id/pk field Django adds that automatically so no need to redeclare the field.
Upvotes: 0
Reputation: 599490
Your primary key is an IntegerField, which means that Django doesn't know it is supposed to autoincrement. Therefore it isn't setting a value automatically.
Change the definition to use an AutoField instead.
Upvotes: 1