9
9
95506682021-01-07 23:51:15
Django
9550668, 2021-01-07 23:51:15

Why is a ManyToMany reference automatically added to the model when a record is created?

Good day to all.

I have a problem with auto-adding a link when creating records in a model.
Model (slightly shortened - removed some of the fields so as not to lose the focus of the question):

class Marathon(models.Model):
    name = models.CharField(
        _("Name"),
        max_length=100,
    )
    creator = models.ForeignKey(
        "users.User",
        on_delete=models.CASCADE,
        related_name="owner",
        related_query_name="marathon_owner",
        verbose_name=_("Marathon creator"),
    )
    avatar = models.ForeignKey(
        "marathons.MarathonAvatar",
        verbose_name=_("Marathon avatar"),
        related_name="marathon",
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
    )
    participants = models.ManyToManyField(
        "users.User",
        related_name="marathon",
        related_query_name="marathon_participants",
        verbose_name=_("Marathon participants"),
        blank=True,
    )


When a user creates a record, the user automatically becomes bound to the creator field (part of the code from the view):
request_data = self.request.POST
request_data._mutable = True
request_data['creator'] = request.user.id
serialization = self.serializer_class(data=request_data, context={'request': request})


But why is the same user automatically added to the participants field of the model? How to avoid it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cgamadeus, 2021-01-11
@cgamadeus

Try putting symmetrical=False in the ManyToManyField field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question