简体   繁体   English

object 在 Django Rest 框架中没有属性

[英]object has no attribute in Django Rest Framework

I develop a mobile application with Django Rest Framework at behind, and React Native at front side.我在后面使用 Django Rest 框架开发了一个移动应用程序,在前端使用 React Native。 I have to models and nested serializers.我必须建模和嵌套序列化程序。 I need to insert record at same time to them.我需要同时向他们插入记录。 But I have 'Entity' object has no attribute 'automobile' error.但我有 'Entity' object has no attribute 'automobile' 错误。 When I check similar examples, I do not understand where I am wrong.当我检查类似的例子时,我不明白我错在哪里。 There will be an entity inserted first, and after that an automobile will inserted with the connection of this entitiy.会先插入一个实体,然后再插入一个连接该实体的汽车。

Could you please help me?请你帮助我好吗?

class Entity(models.Model):

    customer = models.CharField(max_length=100, null=True, blank=True)
    seller = models.CharField(max_length=100, null=True, blank=True)
    entity_name = models.CharField(max_length=50, blank=True, default='')

    class Meta:
        verbose_name_plural = u"Entities"
        verbose_name = u"Entity"
    
    def __str__(self):
        return "%s %s" % (self.id, self.entity_name)

class Automobile(models.Model):
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE, blank=True)

    entity_address = models.CharField(max_length = 250, blank = True, default = '')

    used_km = models.IntegerField(default = 0)

    manufactured_year = models.IntegerField(validators=[MinValueValidator(1900), MaxValueValidator(timezone.now().year)], blank = True, null = True)

    def __str__(self):
        return "%s" % (self.entity_id)
    
    class Meta:
        verbose_name_plural = u"OptionedAutomobiles"
        verbose_name = u"OptionedAutomobile"

class AutomobileSerializer(serializers.ModelSerializer):   

    class Meta:
        model = Automobile
        fields = [ 'entity_address', 'used_km', 'manufactured_year']

class EntitySerializer(serializers.ModelSerializer):
    automobile = AutomobileSerializer(many=False)

    class Meta:
        model = Entity
        fields = ['id', 'customer', 'seller', 'entity_name', 
            'automobile']

    def create(self, validated_data):
        automobile_data = validated_data.pop('automobile')
        entity = Entity.objects.create(**validated_data)
        Automobile.objects.create(entity= entity, **automobile_data)
        return entity

class EntityViewSet(viewsets.ModelViewSet):
    serializer_class = EntitySerializer
    queryset = Entity.objects.all()
    permission_classes = (AllowAny,)

    def perform_create(self, serializer):
        serializer.save(customer=self.request.user)


class AutomobileViewSet(viewsets.ModelViewSet):
    serializer_class = AutomobileSerializer
    queryset = Automobile.objects.all()
    permission_classes = (AllowAny,)
fetch(`http://127.0.0.1:8000/api/entities/`, {
    method: 'POST',
    headers: {
        'Authorization': `Token ${token}`,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({seller:seller, 
        entity_name:entity_name, 
        automobile:{used_km:10}})
    })
    .then((res) => res.json())
    .then((data) => {
      console.log(data)
    })
    
    .then(res =>{
        Alert.alert("Yeni Entity eklendi.");
      })
    .catch(error=>console.log(error));

I could not understand what the problem was, but I solved the problem for now by changing location of create function.我不明白问题出在哪里,但我现在通过更改创建 function 的位置解决了这个问题。 Now, my create function is under AutomobileSerializer, not EntitySerializer.现在,我创建的 function 在汽车序列化器下,而不是实体序列化器下。 Of course I also change something about that, and it solved for now as I said.当然,我也对此进行了一些更改,正如我所说,它现在解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM