代码之家  ›  专栏  ›  技术社区  ›  Jatin Goyal

通过drf中的一个post请求创建互连模型的多个模型实例

  •  0
  • Jatin Goyal  · 技术社区  · 7 年前

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

    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”表中创建了对象。现在,我想使用生成的“booking_id”作为“other”表的相同“booking_id”。如何验证序列化程序并在“其他”表中创建对象,同时保持一致性? 这里有一致性,我的意思是:如果没有错误发生,要么在两个表中都创建对象,如果有错误发生,就不创建对象。

    0 回复  |  直到 7 年前
        1
  •  1
  •   Ozgur Akcali    7 年前

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

    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的defaul createmodelmixin,所有嵌套的对象逻辑都在序列化程序中处理。

    推荐文章