1

我只是在学习 django 和 rest-framework。

我有三个模型 User、UserHospital 和 Timeslots。用户有医院的时间表。我要求用户提供相关医院的所有详细信息,其中显示医院详细信息和时间段。希望以以下格式表示用户详细信息。

我的代码有什么问题?使用视图集和序列化程序是可能的还是我必须尝试另一种方式?

{
    "first_name": "abc",
    "last_name": "xyz",
    "mobile_number":1111111111,
    "related_hospitals": [{
                            "id": 1,
                            "name": "bbbb"
                            "timeslot": [
                {
                    "day": "TUE",
                    "start_time": "09:00:00",
                    "end_time": "15:00:00"
                },
                {
                    "day": "WED",
                    "start_time": "10:00:00",
                    "end_time": "20:00:00"
                }
            ]


                        },
                        {
                         "id": 2,
                        "name": "ccc"
                        "timeslot": []
                        }]

}

创建模型如下:

class Users(models.Model):

    mobile_number = models.BigIntegerField()
    first_name = models.CharField(max_length=255, null=True)
    last_name = models.CharField(max_length=255, null=True)

class TimeSlots(BaseAbstract):

    DAYS = (
        ('SUN', 'sunday'),
        ('MON', 'Monday'),
        ('TUE', 'tuesday'),
        ('WED', 'wednesday'),
        ('THU', 'thursday'),
        ('FRI', 'friday'),
        ('SAT', 'saturday'),

    )

    STATUS = (
        (1, 'HOLIDAY'),
        (2, 'ON_LEAVE'),
        (3, 'AVAILABLE'),
        (4, 'NOT_AVAILABLE')
    )

    DEFAULT_STATUS = 3

    DEFAULT_DAY = "SUN"

    day = models.CharField(default=DEFAULT_DAY, choices=DAYS, max_length=20)
    start_time = models.TimeField()
    end_time = models.TimeField()
    status = models.SmallIntegerField(default=DEFAULT_STATUS, choices=STATUS)

class UserHospital(BaseAbstract):

    user = models.ForeignKey('users.Users', on_delete=models.SET_NULL, null=True)
    name = models.(Hospital,CharField(max_length=255, null=True)
    timeslots = models.ManyToManyField(TimeSlots)

我努力了:

class TimeslotSerializer(serializers.ModelSerializer):
    class Meta:
        model = TimeSlots
        fields = ('day', 'start_time', 'end_time')
        read_only_fields = ('id',)


class RelatedHospitalSerializer(serializers.ModelSerializer):
    timeslot = TimeslotSerializer(many=True)

    class Meta:
        model = UserHospital
        fields = ('name', 'timeslot')
        read_only_fields = ('id',)


class UserDetailsSerializer(serializers.ModelSerializer):
    related_hospitals = serializers.SerializerMethodField()

    def get_related_hospitals(self, obj):
        hospitalData = []
        if UserHospital.objects.all().filter(user=obj).exists():
            hospitalData = UserHospital.objects.all().filter(user=obj)
        return RelatedHospitalSerializer(hospitalData).data

    class Meta:
        model = Users
        fields = ('first_name', 'last_name','mobile_number','related_hospitals')
        read_only_fields = ('id', 'related_hospitals')


class UserDetailsViewset(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = Users.objects.all()
    serializer_class = UserDetailsSerializer    

    def get_queryset(self):

        userid = self.request.query_params.get('userid')
        if userid is not None:
            userData = Users.objects.filter(user=userid)
            return userData
        else:
            return Users.objects.all()

我的代码有什么问题?

4

1 回答 1

1

我建议使用 models.ForeignKey、..ManytoMany 字段等的 related_name 参数 例如,

def Hospital(models.Model):
     user = models.ForeignKey(....., related_name="hospitals")
     ...

def HospitalSerializer(models.Model):
      ...

def UserSerializer(Hyperlinkedmodelserializer ...(or other):
     hospitals = HospitalSerializer(many=True)
     class Meta:
         ....

注意:使用“医院”....

这将自动允许一个人得到一个结果

UserSerializer(userModel, context={'request':request}).data ... 

以您想要的格式

于 2019-11-26T15:58:19.473 回答