如何使用Django REST框架从一个模型发布数据并检索到同一应用程序的另一个模型

dpiehjr4  于 2023-03-31  发布在  Go
关注(0)|答案(1)|浏览(78)

我有两个模型,它们通过一对多的关系相关联。我想使用第一个称为BedNightReturn的模型来发布数据,另一个称为BedNightReturnAssessment来计算数据发布和检索数据。我的模型如下:-

class BedNightReturn(models.Model):
    room_type = models.CharField(max_length=50)
    number_of_rooms = models.PositiveSmallIntegerField()
    price_per_night = models.DecimalField(max_digits=10, decimal_places=2)
    days_in_month = models.PositiveSmallIntegerField()
    
    class Meta:
        verbose_name = 'BedNightReturn'
        verbose_name_plural = 'BedNightReturns'

    def __str__(self):
        return f'{self.room_type}'

class BedNightReturnAssessment(models.Model):
    assessment = models.ForeignKey(BedNightReturn, related_name = "assessments", on_delete=models.CASCADE)
   

    class Meta:
        verbose_name = 'BedNightReturnAssessment'
        verbose_name_plural = 'BedNightReturnAssessments'

    def __str__(self):
        return f'{self.assessment.room_type}'
    
    @property
    def potential_turnover(self) -> float:
        days_in_month = 30
        return float(days_in_month) * float(self.assessment.number_of_rooms) * float(self.assessment.price_per_night)
    
    @property
    def actual_turnover(self) -> float:
        return float(self.assessment.days_in_month) * float(self.assessment.number_of_rooms) * float(self.assessment.price_per_night)

和序列化器如下:-

class BedNightReturnSerializer(ModelSerializer):
    class Meta:
        model = BedNightReturn
        fields = (
            'id',
            'room_type',
            'number_of_rooms',
            'price_per_night',
            'days_in_month',
            
        )

class BedNightReturnAssessmentSerializer(ModelSerializer):
    assessment = BedNightReturnSerializer()
    potential_turnover = ReadOnlyField()
    actual_turnover = ReadOnlyField()
    class Meta:
        model = BedNightReturnAssessment
        fields = (
            'id',
            'assessment',
            'potential_turnover',
            'actual_turnover',
        )

意见如下:

class BedNightReturnViewSet(ModelViewSet):
    queryset = BedNightReturn.objects.all()
    serializer_class = BedNightReturnSerializer

class BedNightReturnAssessmentViewSet(ModelViewSet):
    queryset = BedNightReturnAssessment.objects.all()
    serializer_class = BedNightReturnAssessmentSerializer

和网址:-

from django.urls import include, path
from rest_framework import routers

from bednightlevy.views import (
    BedNightReturnAssessmentViewSet,
    BedNightReturnViewSet,
)

router = routers.DefaultRouter(trailing_slash = False)

router.register('returns', BedNightReturnViewSet, basename="bednight")
router.register('assessments', BedNightReturnAssessmentViewSet, basename='bednight_assessment')

urlpatterns = [
    path('',include(router.urls)),
]

我们的想法是使用 /returns 端点来发布数据,使用 /assessments 端点来检索数据(只读)。

3pvhb19x

3pvhb19x1#

使用BedNightReturnSerializer中的create函数发布数据。

class BedNightReturnSerializer(ModelSerializer):
    class Meta:
        model = BedNightReturn
        fields = (
            'id',
            'room_type',
            'number_of_rooms',
            'price_per_night',
            'days_in_month',
        )

    def create(self, validated_data):
        with transaction.atomic():
            BedNightReturn.objects.create(**validated_data)

相关问题