因此,在计划中,我创建了一个外键来链接系列内部,以便在其中包含系列成员ID。
以下是我的日程安排API的样子:https://imgur.com/a/bwYDn
这是我的问题。
正如您在上面的链接中看到的那样,userId是一个下拉列表。有可能使它成为userId = self.request.user.userId?
在计划api中,familyId是一个由所有家庭成员组成的下拉列表(基本上,甚至是其他添加了他们家人的人),是否有办法过滤它以便它只显示下拉列表只有当前用户familyId出现?
创建计划时,用户只能插入1个familyId。有没有办法选择超过1个familyId?例如,用户可以插入familyId 1和2
这是我的代码
models.py
class MyUser(AbstractUser):
userId = models.AutoField(primary_key=True)
gender = models.CharField(max_length=6, blank=True, null=True)
nric = models.CharField(max_length=40, blank=True, null=True)
birthday = models.DateField(blank=True, null=True)
birthTime = models.TimeField(blank=True, null=True)
class Family(models.Model):
userId = models.ForeignKey(MyUser)
relationship = models.CharField(max_length=100)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
gender = models.CharField(max_length=6, blank=True, null=True)
nric = models.CharField(max_length=40, blank=True, null=True)
class Schedule2(models.Model):
userId = models.ForeignKey(MyUser, on_delete=models.CASCADE)
familyId = models.ForeignKey(Family, on_delete=models.CASCADE)
date = models.DateField()
time = models.TimeField()
location = models.CharField(max_length=255, blank=True, null=True)
title = models.Charfield(max_length=100, blank=True, null=True)
desc = models.CharField(max_length=300, blank=True, null=True)
serializer.py
class FamilySerializer(serializers.ModelSerializer):
class Meta:
model = Family
fields = ('id', 'userId', 'first_name', 'last_name', 'gender', 'nric', 'relationship')
class Schedule2Serializer(serializers.ModelSerializer):
valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p']
time = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats)
class Meta:
model = Schedule2
fields = ('id', 'userId', 'familyId', 'title', 'desc', 'date', 'time', 'location')
视图
class FamilyViewSet(viewsets.ModelViewSet):
permission_classes = [AllowAny]
queryset = Family.objects.all()
serializer_class = FamilySerializer
# this is to allow current user to see their own family only
def get_queryset(self):
user = self.request.user
return Family.objects.filter(userId=user)
class ScheduleViewSet2(viewsets.ModelViewSet):
permission_classes = [AllowAny]
queryset = Schedule2.objects.all()
serializer_class = Schedule2Serializer
答案 0 :(得分:0)
第一个问题的答案是“是”,您可以将模型中的user_id
设置为登录用户的ID(self.request.user
)。为此,您将不得不覆盖create方法。