我在Bcustomer应用程序中有一个扩展django用户模型的客户模型,因此我将保存基本详细信息,例如用户表中的名称和客户表中的剩余数据(城市等)。
当我通过API调用以下代码时,它会显示以下错误。但数据在表中保存。我还想为这个api实现get和put调用。
Got AttributeError when attempting to get a value for field `city` on serializer `CustomerSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'city'.
我的Bcustomer / models.py
class BCustomer(models.Model):
customer = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True, blank=True )
address = models.CharField(max_length=50)
city = models.CharField(max_length=256)
state = models.CharField(max_length=50)
user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True, on_delete=models.CASCADE, related_name='customer_creator')
# more fields to go
def __str__(self):
# return str(self.name) (This should print first and last name in User model)
class Meta:
app_label = 'bcustomer'
我的Bcustomer / serializers.py
from django.contrib.auth import get_user_model
from models import BCustomer
class CustomerSerializer(serializers.HyperlinkedModelSerializer):
city = serializers.CharField()
class Meta:
model = get_user_model()
fields = ('first_name', 'email','city')
def create(self, validated_data):
userModel = get_user_model()
email = validated_data.pop('email', None)
first_name = validated_data.pop('first_name', None)
city = validated_data.pop('city', None)
request = self.context.get('request')
creator = request.user
user = userModel.objects.create(
first_name=first_name,
email=email,
# etc ...
)
customer = BCustomer.objects.create(
customer=user,
city=city,
user=creator
# etc ...
)
return user
my Bcustomer/views.py
class CustomerViewSet(viewsets.ModelViewSet):
customer_photo_thumb = BCustomer.get_thumbnail_url
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = BCustomer.objects.all()
serializer_class = CustomerSerializer
我的Bcustomer / urls.py
router.register(r'customer', views.CustomerViewSet, 'customers')
POST请求格式
{
"first_name":"Jsanefvf dss",
"city":"My City",
"email":"myemail@gmail.com",
#more fields
}
我还需要为这个api实现put和get。现在数据在两个表中保存,但显示错误。
答案 0 :(得分:0)
当然有抱怨。
验证顺利,创建但一旦创建,视图将反序列化结果并将其返回给客户端。
这是南下的地方。 Serializer被配置为认为city
是默认用户的字段,而它实际上是BCustomer
的一部分。为了解决这个问题,您应该将source
参数设置为city
字段。您可能需要更新序列化程序的create
/ update
以反映该更改,不确定该更改。