Home > Net >  How to automatically set ManyToMany relationship with user
How to automatically set ManyToMany relationship with user

Time:05-25

How to automatically set owner field with the user which creates this event?

Event model:

class Event(models.Model):
    title = models.CharField(max_length=50, unique=True)
    describe = models.TextField(max_length=500)
    type_of_event = models.IntegerField(choices=TYPE_OF_EVENT_CHOICE, default=0)
    img = models.ImageField(null=True, blank=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    event_date = models.DateTimeField()
    city = models.ForeignKey(City, verbose_name='City', on_delete=models.CASCADE)
    address = models.CharField(max_length=60)
    ticket_price = models.IntegerField(default=0)
    email = models.EmailField(max_length=100, verbose_name='Contact email',
                              validators=[validate_email])

Event`s view:

class CreateEventView(generics.CreateAPIView):
    serializer_class = EventDetailSerializer
    permission_classes = [IsAuthenticated]

Event`s serializer:

class EventDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Event
        fields = ['title', 'img', 'type_of_event', 'describe', 'event_date', 'city', 'address',
                  'ticket_price', 'email']

CodePudding user response:

You can achieve that by overriding the perform_create method of your CreateEventView, something like this:

class CreateEventView(generics.CreateAPIView):
    serializer_class = EventDetailSerializer
    permission_classes = [IsAuthenticated]

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

And as David pointed out, keep in mind that a ForeignKey is not a a many-to-many relation, that would be a ManyToManyField. Given the context, I assume the ForeignKey (owner) is actually the desired behavior, so all good.

  • Related