0

我在Bcustomer应用程序中有一个客户模型,它扩展了django用户模型,因此我将在User表中保存诸如名称之类的基本信息,其余数据城市等)在客户表中。Django rest框架:扩展客户的用户模型 - 一对一

当我通过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":"[email protected]", 
    #more fields 
} 

我还需要执行put和get api。现在数据保存在两个表中,但显示错误。

+0

如果'CustomerSerializer'应该序列化'BCustomer',那么为什么模型设置为'get_user_model'? –

回答

0

当然,它抱怨。

验证进行得很顺利,创建一旦创建,视图将反序列化结果并将其返回给客户端。

这是它向南的点。串行器被配置为认为city是默认用户的字段,而它实际上是BCustomer的一部分。为了解决这个问题,您应该将source参数设置为city字段。您可能需要更新序列化程序的create/update以反映该更改,不确定该更改。