[Fixed]-Django giving Cannot force an update in save() with no primary key

18👍

You need to use the * and ** when you call super as well:

super(Categories, self).save(*args, **kwargs)

Note there are some other strange things in this code too. Primarily this line:

parent = Categories.objects.get(id=self.ParentCategoryID.id)

is doing two identical queries for no reason; self.ParentCategoryID is already the parent object. You should just do:

parent = self.ParentCategoryID

which should lead you to the conclusion that the ParentCategoryID is badly named; it contains the actual object, not the ID.

Note also that there are quite a few style violation; Python prefers lower_case_with_underscore for attribute names, and Django prefers singular model names. The related name for the foreign key should be plural, though, as it will refer to multiple category objects. So:

class Category(models.Model):
    name = models.CharField(max_length=155)
    code = models.CharField(max_length=255)
    parent_category = models.ForeignKey('self', related_name='sub_categories', null=True, blank=True)
    ...

Leave a comment