# override model save method

**URL:** <https://forum.djangoproject.com/t/override-model-save-method/9555>\
**Category:** Using the ORM\
**Created:** [September 4, 2021, 10:03am UTC](https://forum.djangoproject.com/t/override-model-save-method/9555 "2021-09-04T10:03:52Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![smjt2000](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/smjt2000/32/5729_2.png) [@smjt2000](https://forum.djangoproject.com/u/smjt2000)\
**Post date:** [September 4, 2021, 10:03am UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/1 "2021-09-04T10:03:52Z")

</div>

I have a product model that have a ManyToManyFiled to Category model.  
category model has a ForeignKey to itself named parent, I want to add parent categories to product while saving but there is a problem.  
it’s my code:

```auto
` def save(self, *args, **kwargs):
        for cat in self.category.all():
            if cat.parent:
                self.category.add(cat.parent)
        super(Product, self).save(*args, **kwargs)`

```

it doesn’t work but when I print **cat** it prints the parent but nothing changed in model.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 4, 2021, 11:59am UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/2 "2021-09-04T11:59:40Z")

</div>

Do you get any error or stack trace from this, or is this just not appearing to be saved?

How do you know nothing is being changed in the model? (Keep in mind that a many-to-many field assignment does not change either model - the entries are made in the [“join table”](https://docs.djangoproject.com/en/3.2/ref/models/fields/#id1).)

It might be helpful at this point if you posted the complete model, view and form(s) involved with this.

---

<div class="post-metadata">

**Author:** ![smjt2000](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/smjt2000/32/5729_2.png) [@smjt2000](https://forum.djangoproject.com/u/smjt2000)\
**Post date:** [September 4, 2021, 12:10pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/3 "2021-09-04T12:10:21Z")

</div>

I checked the model in admin panel, nothing changed.

Product model:

```auto
class Product(models.Model):
    STATUS_CHOICES = (
        ('s', 'show'),
        ('h', 'hide'),
    )
    title = models.CharField(max_length=150)
    slug = models.SlugField(max_length=170, unique=True)
    category = models.ManyToManyField(Category)
    thumbnail = models.ImageField(upload_to='images/products', default='images/no-image-available.png')
    image_list = ImageSpecField(source='thumbnail', processors=[ResizeToFill(400, 200)], format='JPEG',
                                options={'quality': 75})
    image_detail = ImageSpecField(source='thumbnail', processors=[ResizeToFill(1000, 500)], format='JPEG',
                                  options={'quality': 100})
    description = models.TextField()
    inventory = models.IntegerField()
    features = models.ManyToManyField(Feature)
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='s')

    def __str__ (self):
        return self.title

    class Meta:
        verbose_name = "product"
        verbose_name_plural = "products"

    def save(self, *args, **kwargs):
        for cat in self.category.all():
            if cat.parent:
                self.category.add(cat.parent)
        return super(Product, self).save(*args, **kwargs)

```

Category model:

```auto
class Category(models.Model):
    parent = models.ForeignKey('self', default=None, null=True, blank=True, on_delete=models.SET_NULL,
                               related_name='children')
    title = models.CharField(max_length=40)
    slug = models.SlugField()
    status = models.BooleanField(default=True)

    def __str__ (self):
        return self.title

    class Meta:
        verbose_name = "category"
        verbose_name_plural = "categories"
        ordering = ["parent_id"]

    objects = CategoryManager()

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 4, 2021, 12:21pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/4 "2021-09-04T12:21:38Z")

</div>

> [@smjt2000](#):
>
> ```auto
> for cat in self.category.all():
> if cat.parent:
> self.category.add(cat.parent)
> 
> ```

How is the first category assigned? (When the Product is first created, self.category.all is going to be an empty set.)

This is where it may be helpful to also see the views and forms involved.

---

<div class="post-metadata">

**Author:** ![smjt2000](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/smjt2000/32/5729_2.png) [@smjt2000](https://forum.djangoproject.com/u/smjt2000)\
**Post date:** [September 4, 2021, 1:10pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/5 "2021-09-04T13:10:11Z")

</div>

so what can I do to do that ?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 4, 2021, 1:53pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/6 "2021-09-04T13:53:10Z")

</div>

Do what? What are you trying to accomplish here?

---

<div class="post-metadata">

**Author:** ![Rigo-Villalta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/rigo-villalta/32/5667_2.png) [@Rigo-Villalta](https://forum.djangoproject.com/u/Rigo-Villalta)\
**Post date:** [September 4, 2021, 1:56pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/7 "2021-09-04T13:56:04Z")

</div>

I have a similar problems and solved with:

```auto
def save(self, *args, **kwargs):
     super(Product, self).save(*args, **kwarg)
        for cat in self.category.all():
            if cat.parent:
                self.category.add(cat.parent)
    super(Product, self).save(*args, **kwarg)

```

I am not sure why but it worked. I think is because you need first a instance to reference your many to many relation, before iterate over it.

---

<div class="post-metadata">

**Author:** ![smjt2000](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/smjt2000/32/5729_2.png) [@smjt2000](https://forum.djangoproject.com/u/smjt2000)\
**Post date:** [September 4, 2021, 3:44pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/8 "2021-09-04T15:44:43Z")

</div>

I want to add parents of selected category to product categories.  
example :  
digital appliance-\> **None** \_\_ Mobile-\> **digital appliance** \_\_ Samsung-\> **Mobile** and…

when choose _Samsung_ for category of a product, I want to add _Mobile_ and _digital appliance_ to category

---

<div class="post-metadata">

**Author:** ![smjt2000](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/smjt2000/32/5729_2.png) [@smjt2000](https://forum.djangoproject.com/u/smjt2000)\
**Post date:** [September 4, 2021, 3:47pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/9 "2021-09-04T15:47:15Z")

</div>

thanks but it doesn’t work…

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 4, 2021, 3:49pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/10 "2021-09-04T15:49:23Z")

</div>

So this goes back to my earlier response. How are you selecting a category? What does the view and form being used look like?

---

<div class="post-metadata">

**Author:** ![smjt2000](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/smjt2000/32/5729_2.png) [@smjt2000](https://forum.djangoproject.com/u/smjt2000)\
**Post date:** [September 4, 2021, 3:55pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/11 "2021-09-04T15:55:05Z")

</div>

for now, I’m doing it from admin panel.  
this is an new project and doesn’t have forms or anything else.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 4, 2021, 3:57pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/12 "2021-09-04T15:57:57Z")

</div>

So after you have assigned a category, have you verified that the assignment was made in the join table?

---

<div class="post-metadata">

**Author:** ![smjt2000](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/smjt2000/32/5729_2.png) [@smjt2000](https://forum.djangoproject.com/u/smjt2000)\
**Post date:** [September 4, 2021, 4:27pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/13 "2021-09-04T16:27:52Z")

</div>

in template I made a section for showing categories, it shows here. and in admin panel.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 4, 2021, 6:04pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/14 "2021-09-04T18:04:07Z")

</div>

Ok, we need to see all the code that’s part of this.

---

<div class="post-metadata">

**Author:** ![smjt2000](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/smjt2000/32/5729_2.png) [@smjt2000](https://forum.djangoproject.com/u/smjt2000)\
**Post date:** [September 4, 2021, 7:50pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/15 "2021-09-04T19:50:27Z")

</div>

models code is [here](https://paste.ubuntu.ir/dszi)

---

<div class="post-metadata">

**Author:** ![Rigo-Villalta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/rigo-villalta/32/5667_2.png) [@Rigo-Villalta](https://forum.djangoproject.com/u/Rigo-Villalta)\
**Post date:** [September 4, 2021, 9:17pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/16 "2021-09-04T21:17:55Z")

</div>

I have found the problem @smjt2000 .

**Edited: Override the save method works, but doesn’t change the way that ManyToMay relations are managed in the Admin Site when save an object.**.

First /[override the save()method of the models doesn’ t work in the Admin Site](https://stackoverflow.com/questions/33527533/django-override-default-save-add-manytomany) . Your code works for non Admin Forms and Views.

So you need the follow code in your admin.py file:

```auto
class ProductAdmin(admin.ModelAdmin):

    model = Product

    def save_related(self, request, form, formsets, change):

        super().save_related(request, form, formsets, change)

        for cat in form.instance.category.all():

            form.instance.category.add(cat.parent)

admin.site.register(Product, ProductAdmin)

```

Try it, it will work, I have manually tested it.

PD: I think this is a anti-DRY behavior of the Admin Site, but that is what we have.

---

<div class="post-metadata">

**Author:** ![smjt2000](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/smjt2000/32/5729_2.png) [@smjt2000](https://forum.djangoproject.com/u/smjt2000)\
**Post date:** [September 4, 2021, 10:25pm UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/17 "2021-09-04T22:25:34Z")

</div>

Thank you. it’s working. but working just for one parent of each selected category.  
for add all parents(parent of parent and…) :

```auto
class ProductAdmin(admin.ModelAdmin):
    model = Product

    def save_related(self, request, form, formsets, change):
        super().save_related(request, form, formsets, change)

        for cat in form.instance.category.all():
            _cat = cat.parent
            while _cat:
                print(_cat)
                form.instance.category.add(_cat)
                _cat = _cat.parent

admin.site.register(Product, ProductAdmin)

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 5, 2021, 12:38am UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/18 "2021-09-05T00:38:04Z")

</div>

> [@Rigo-Villalta](#):
>
> First [override the save()method of the models doesn´t work in the Admin Site](https://stackoverflow.com/questions/33527533/django-override-default-save-add-manytomany). Your code works for non Admin Forms and Views.

That is a dangerously wrong mischaracterization of the real situation.

Overriding save _does_ work in the Admin. The issue is that saving entries in a ManyToMany relationship does not change the base table - that’s a distinction important to understand.

---

<div class="post-metadata">

**Author:** ![Rigo-Villalta](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/rigo-villalta/32/5667_2.png) [@Rigo-Villalta](https://forum.djangoproject.com/u/Rigo-Villalta)\
**Post date:** [September 5, 2021, 3:44am UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/19 "2021-09-05T03:44:28Z")

</div>

You are right. @KenWhitesell. I will edit my answer in order to avoid confusions.

---

<div class="post-metadata">

**Author:** ![smjt2000](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/smjt2000/32/5729_2.png) [@smjt2000](https://forum.djangoproject.com/u/smjt2000)\
**Post date:** [September 5, 2021, 8:06am UTC](https://forum.djangoproject.com/t/override-model-save-method/9555/20 "2021-09-05T08:06:56Z")

</div>

Is there a better way or I should not do this?

[Next page](https://forum.djangoproject.com/t/override-model-save-method/9555.md?page=2)
