我正在尝试为用户创建一个RESTApi以便加入我的应用程序中的特定组。我有以下模型:用户,组,然后在字段成员下将用户与组进行ManytoMany连接
我尝试使用不同的视图和序列化器,或者我无法获取queryset或此错误:
“ max_no_members”列中的空值违反了非空约束 详细信息:失败行包含(11,,d85743a7-ccd9-4175-984b-86c10c75aec6,null,null,,null,2019-07-25 18:11:34.9933 + 00,t,null,每月)。
views.py
class GroupJoinAPIView(CreateAPIView):
queryset = Groups.objects.annotate(arr=ArrayAgg('members')).values_list('id', 'arr')
serializer_class = JoinGroupSerializer
permission_classes = [IsAuthenticated]
def perform_create(self, serializer):
print(sys.stderr, self.queryset)
if self.request.user.id in self.queryset.all():
return 'User already in the group'
else:
list(self.queryset.all()).append(self.request.user.id)
serializer.save()
serializers.py
class JoinGroupSerializer(serializers.ModelSerializer):
users = UserSerializer(many=True, read_only = True)
class Meta:
model = Groups
fields = ['members','users']
urls.py
path('<int:pk>/join', GroupJoinAPIView.as_view(), name='members'),
models.py(Groups)
class Groups(models.Model):
name = models.CharField(max_length = 50, unique = True)
group_id = models.UUIDField(default = uuid.uuid4, editable = False)
max_no_members = models.PositiveIntegerField()
savings_amount = models.PositiveIntegerField()
savings_type = models.CharField(max_length = 10, default = 'Monthly')
description = models.TextField(blank=True)
begin_date = models.DateField()
created_date = models.DateTimeField(auto_now_add=True)
searchable = models.BooleanField(default = True)
members = models.ManyToManyField(User, related_name='group_members')
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete =models.CASCADE,related_name='group_admin' )
def __str__(self):
return self.name
我希望能够将经过身份验证的用户添加为组的成员。
像api / group / 3 / join一样,这将带来一个经过身份验证的用户加入的形式。如果他是会员,则应该删除一条用户已经存在的消息