# Adding elements to a ManyToMany field inside the clean() method of a model.

**URL:** <https://forum.djangoproject.com/t/adding-elements-to-a-manytomany-field-inside-the-clean-method-of-a-model/34512>\
**Category:** Using the ORM\
**Created:** [September 5, 2024, 11:10am UTC](https://forum.djangoproject.com/t/adding-elements-to-a-manytomany-field-inside-the-clean-method-of-a-model/34512 "2024-09-05T11:10:47Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![marc406](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/marc406/32/23721_2.png) [@marc406](https://forum.djangoproject.com/u/marc406)\
**Post date:** [September 5, 2024, 11:10am UTC](https://forum.djangoproject.com/t/adding-elements-to-a-manytomany-field-inside-the-clean-method-of-a-model/34512/1 "2024-09-05T11:10:47Z")

</div>

I am trying to automatically add a user to a ManyToMany field inside the clean() method of the Project class if a project gets added or updated:

```python
class Project(models.Model):
    title = models.CharField(max_length=100, validators=[validate_project_title], verbose_name='Title', unique=True, null=True)
    assigned_to = models.ManyToManyField(User)
    
        
    def clean(self):
        super().save()

        project = Project.objects.get(title=self.title)

        try: # Check if the "admin" user exists in the system
            admin_user = User.objects.get(username='admin')
        except User.DoesNotExist:
            raise ValidationError('The "admin" user does not exist.')
        
        if admin_user not in project.assigned_to.all(): #adding the admin user to the users assined to the project
            project.assigned_to.add(admin_user)

```

But on the creation of a new model or the update of an existing model only the users choosen in the gui are added to the object. (The code runs without prompting any errrors. )

---

<div class="post-metadata">

**Author:** ![cliff688](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/cliff688/32/22816_2.png) [@cliff688](https://forum.djangoproject.com/u/cliff688)\
**Post date:** [September 5, 2024, 1:45pm UTC](https://forum.djangoproject.com/t/adding-elements-to-a-manytomany-field-inside-the-clean-method-of-a-model/34512/2 "2024-09-05T13:45:17Z")

</div>

Hello @marc406 !

Here are some things you might want to consider:

The `clean()` method is generally used for data validation in _preparation_ for saving a model. You must not call the `save()` method here.

For checking whether an instance exists in the database, it’s better to use the `exists()` method on a Queryset.

```auto
class Project(models.Model):
    title = models.CharField(max_length=255, validators=[validate_project_title], verbose_name='Title', unique=True, null=True)
    assigned_to = models.ManyToManyField(User)

    def clean(self):
        super().clean() # Call the superclass clean method

        # Check if "admin" user exists using exists
        if not User.objects.filter(username='admin').exists():
            raise ValidationError('The "admin" user does not exist.')

    def save(self, *args, **kwargs):
        # Call superclass save method to save the object
        super().save(*args, **kwargs)

        # Ensure "admin" user is assigned to the project here
        admin_user = User.objects.get(username='admin')
        if admin_user not in self.assigned_to.all():
            self.assigned_to.add(admin_user)

```

Note however that the `clean()` method is not automatically called when you save a model instance. You will have to call it yourself before saving.

---

<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, 2024, 2:50pm UTC](https://forum.djangoproject.com/t/adding-elements-to-a-manytomany-field-inside-the-clean-method-of-a-model/34512/3 "2024-09-05T14:50:11Z")

</div>

Welcome @marc406 !

In addition to the above:

> [@marc406](#):
>
> ```auto
> project = Project.objects.get(title=self.title)
> 
> ```

There’s no need to issue this query. This is the `clean` method of this instance of `Project`. You can refer to the current object as `self`.

Also, according to the docs at [Many-to-many relationships | Django documentation | Django](https://docs.djangoproject.com/en/5.1/topics/db/examples/many_to_many/#many-to-many-relationships), you don’t need to check for existance of a relationship. By default, Django will not create duplicate entries.

That means that this:

> [@marc406](#):
>
> ```auto
> if admin_user not in project.assigned_to.all():
> project.assigned_to.add(admin_user)
> 
> ```

would more appropriately be:

```auto
self.assigned_to.add(admin_user)

```
