如何自动设置与用户的多对多关系

How to automatically set ManyToMany relationship with user

如何自动为创建此事件的用户设置所有者字段?

事件模型:

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])

活动观点:

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

事件的序列化程序:

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

您可以通过重写 CreateEventViewperform_create 方法来实现,如下所示:

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

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

正如大卫指出的那样,请记住 ForeignKey 而不是 many-to-many 关系,那将是 ManyToManyField .鉴于上下文,我假设 ForeignKey(所有者)实际上是所需的行为,所以一切都很好。