我想根据一个发帖请求创建两个条目。一种是“日期”模型,另一种是“其他”模型。两种型号对应的代码如下所示。
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”用作“其他”表的相同“ booking_id”。如何在保持一致性的同时验证序列化程序并在“其他”表中创建对象? 这里的一致性是指:如果没有错误发生,请在两个表中都创建对象,或者如果发生任何错误,则不创建对象。
答案 0 :(得分: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,所有嵌套对象逻辑都在序列化程序中处理。