通过DRF中的一个发布请求创建多个相互关联模型的模型实例

问题描述 投票:0回答:1

我想从一个帖子请求中创建两个条目。一个在'日期'模型中,一个在'其他'模型中。两种型号对应的代码如下所示。

class Dates(models.Model):
  booking_id = models.AutoField(primary_key=True)
  timestamp = models.DateTimeField(auto_now_add=True)
  feedback = models.CharField(max_length=8, default='no')
  myself = models.BooleanField(default=True)

  class Meta:
    app_label = 'bookings'

其他是:

class Other(models.Model):
  booking_id = models.OneToOneField(
                'bookings.Dates',
                null=False,
                default=1,
                primary_key=True,
                on_delete=models.CASCADE
            )
  name = models.CharField(max_length=64)
  phone_number = models.CharField(max_length=14)
  email_id = models.EmailField(max_length=128)

  class Meta:
    app_label = 'bookings'

我已经验证了Dates Serializer中的数据,并在'Dates'表中创建了该对象。现在,我想使用生成的'booking_id'作为'Other'表的相同'booking_id'。如何在保持一致性的同时验证序列化程序并在“其他”表中创建对象?这里有一致性,我的意思是:如果没有错误发生,则在两个表中创建对象,或者如果发生任何错误,则不创建对象。

django post django-models django-rest-framework serializer
1个回答
1
投票

您可以使用可写嵌套序列化器来实现此目的。您需要为其他模型定义序列化程序类,然后您的日期序列化程序可能如下所示:

class DatesSerializer(serializers.ModelSerializer):
    other = OtherSerializer()

    class Meta:
        model = Dates
        fields = ('timestamp', 'feedback', 'myself', 'other')

    def validate_other(self, value):
        # Run validations for Other model here, either manually or through OtherSerializer's is_valid method. You won't have booking_id in value here though, take that into account when modelling your validation process

    def validate_feedback(self, value):
        # Run validations specific to feedback field here, if necessary. You can do this for all serializer fields

    def validate(self, data):
        # Run non-field specific validations for Dates here

    def create(self, validated_data):
        # At this point, validation for both models are run and passed

        # Pop other model data from validated_data first
        other_data = validated_data.pop('other')

        # Create Dates instance 
        dates = Dates.objects.create(**validated_data)

        # Create Other instance now
        Other.objects.create(booking_id=dates, **other_data)

        return dates

您可以在此处使用DRF的默认CreateModelMixin,所有嵌套对象逻辑都在序列化程序中处理。

© www.soinside.com 2019 - 2024. All rights reserved.