Python 向序列化程序添加相关字段时出现问题
我有两个类,分别是Python 向序列化程序添加相关字段时出现问题,python,django,django-serializer,Python,Django,Django Serializer,我有两个类,分别是Land和UTMPoint: class UTMPoint(models.Model): x = models.CharField(max_length=20) y = models.CharField(max_length=20) z = models.CharField(max_length=20) land = models.ForeignKey('Land', on_delete=models.DO_NOTHING) 它们的序列化程序是
Land
和UTMPoint
:
class UTMPoint(models.Model):
x = models.CharField(max_length=20)
y = models.CharField(max_length=20)
z = models.CharField(max_length=20)
land = models.ForeignKey('Land', on_delete=models.DO_NOTHING)
它们的序列化程序是:
class UTMPointsSerializer(serializers.ModelSerializer):
class Meta:
model = UTMPoint
fields = ('id', 'x', 'y', 'z', 'land',)
read_only_fields = ('id',)
class LandSerializer(serializers.ModelSerializer):
user = UserSerializer()
utm_points = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Land
fields = ('id', 'user', 'activity_field','activity_location',
'area', 'part', 'location','verification_code', 'verified',
'description', 'approved', 'receipt_bank_name', 'receipt_serial',
'receipt_date', 'receipt_amount','utm_points',)
read_only_fields = ('id', 'approved',)
def create(self, validated_data):
user = validated_data.pop('user')
user = User.objects.create(**user)
user.save()
land = Land.objects.create(user=user,**validated_data)
land.save()
return land
如您所见,Land
具有utm\u点
相关字段,但当我运行此测试时:
def test_create_land(self):
"""test creating land"""
payload = {
'activity_field': 'farming',
'user': {'national_code': '12333', 'password': 'passW@rd'},
'activity_location': 'Kermanshah',
'area': 'sw',
'part': 'sp',
'location': 'the old address',
'verification_code': '1',
'verified': '0',
'description': 'sb is calling for it',
'approved': True,
'receipt_bank_name': 'meili',
'receipt_serial': '12312',
'receipt_amount': '10000',
}
res = self.client.post(LAND_URL, payload, format='json')
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
我发现这个错误AttributeError:“Land”对象没有属性“utm\u points”
我不知道为什么这个错误是抛出
Land
正确的相关字段utm\u点
,所以为什么会发生?不,您需要在utm\u点
模型的Land
字段中添加related\u name
:
class UTMPoint(models.Model):
x = models.CharField(max_length=20)
y = models.CharField(max_length=20)
z = models.CharField(max_length=20)
land = models.ForeignKey('Land', on_delete=models.DO_NOTHING, related_name='utm_points'). # <-- Here
class-UTMPoint(models.Model):
x=models.CharField(最大长度=20)
y=models.CharField(最大长度=20)
z=models.CharField(最大长度=20)
land=models.ForeignKey('land',on\u delete=models.DO\u NOTHING,related\u name='utm\u points')#