Django Rest Framework中'Entity'无'automobile'属性问题求助
Hey there! Let's break down why you're hitting that error and how to fix it quickly.
The Root Cause
Your Entity model doesn't actually have an automobile attribute—here's why:
When you set up a ForeignKey from Automobile to Entity, Django automatically creates a reverse relationship on the Entity model. By default, this relationship is named automobile_set (it follows the pattern [model_name]_set). But your EntitySerializer is trying to access an attribute named automobile, which doesn't exist, hence the error.
Solution 1: Add a related_name to the Foreign Key
The cleanest fix is to explicitly name the reverse relationship in your Automobile model so it matches what your serializer expects:
class Automobile(models.Model): # Add related_name='automobile' to the ForeignKey field entity = models.ForeignKey(Entity, on_delete=models.CASCADE, blank=True, related_name='automobile') 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"
This tells Django to use automobile as the name for the reverse relationship from Entity to Automobile, which matches exactly what your serializer is looking for.
Solution 2: Update the Serializer to Use the Default Reverse Name
If you don't want to modify the model, you can adjust the serializer to reference Django's default reverse relationship name using the source parameter:
class EntitySerializer(serializers.ModelSerializer): # Use source to point to Django's default reverse relationship name automobile = AutomobileSerializer(many=False, source='automobile_set') 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
Why Your Create Logic is Already Correct
Good news—your create method in EntitySerializer is properly structured:
- It extracts the automobile data from the validated payload
- Creates the
Entityfirst - Creates the
Automobileand links it to the newEntity
Once you fix the reverse relationship naming issue, this logic will work as expected, and your frontend request (which is correctly formatted with the nested automobile object) will create both records without errors.
Quick Test
After applying either fix, send your frontend request again—you should see both the Entity and Automobile records created in your database, and the error should be gone.
内容的提问来源于stack exchange,提问作者Ahmet Tütüncüler

