如何通过django rest框架从多个表发送响应数据



我想发送响应(xyzSerializer.data),其中xyzSerializer序列化数据从两个模型,即用户和客户给它以下正文/看

{
'userID': 1, 
'firstName': 'name', 
'lastName': 'Lname', 
'gender': 'Male', 
'country': 'Cloc', 
'city': 'City', 
'phoneNumber': '12345', 
'dob': 'dd-mm-yy', 
'dateJoined': 'dd-mm-yy', 
'role': 'blogger', 
'user': 1
'customerID': 1,
'occupation': '',
'blogger': True,
'userID': 1
}

但是,目前我可以分别序列化用户模型或客户模型,它们分别给出以下输出:

UserSerializer
{
'userID': 1, 
'firstName': 'name', 
'lastName': 'Lname', 
'gender': 'Male', 
'country': 'Cloc', 
'city': 'City', 
'phoneNumber': '12345', 
'dob': 'dd-mm-yy', 
'dateJoined': 'dd-mm-yy', 
'role': 'blogger', 
'user': 1
}
CustomerSerializer
{
'customerID': 1,
'occupation': '',
'blogger': True,
'userID': 1
}

我想使用

连接来自两个模型的数据

userID

,并将其作为响应发送。

这是我的用户和客户模型,

class Users(models.Model):
userID = models.AutoField(primary_key=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
firstName = models.TextField()
lastName = models.TextField()    
gender = models.TextField()
country = models.TextField()
city = models.TextField()
phoneNumber = models.TextField()
dob = models.TextField()
dateJoined = models.TextField()
role = models.TextField()
def __str__(self):
return f"ID: {self.userID}"
class Customers(models.Model):
customerID = models.AutoField(primary_key=True)
userID = models.ForeignKey('Users', on_delete=models.CASCADE, name="userID")
occupation = models.TextField()
blogger = models.BooleanField(default= False)
def __str__(self):
return f"ID: {self.customerID}"

这是我的序列化器,

class UserSerializer(ModelSerializer):
class Meta:
model = Users
fields = '__all__'
class CustomerSerializer(ModelSerializer):
class Meta:
model = Customers
fields = '__all__'

这是我的观点:

@api_view(['GET'])
def getUserByIDDemo(request, uName, pWord):    
username = uName
password = pWord
userObj = authenticate(request, username=username, password=password)
# Check if authentication successful
if userObj is not None:
login(request, userObj)
currentUser = Users.objects.get(user = userObj)
userializer = UserSerializer(currentUser, many = False)
customer = Customers.objects.get(customerID = userializer.data['userID'])
cserializer = CustomerSerializer(customer, many = False)
print(userializer.data)
print(cserializer.data)

#following two lines I tried concatinating data but that gave error
#xyz = cserializer.data + userializer.data
#print(xyz)

#Here I want to send data from both models joined by userID
return Response(cserializer.data)
else:
message = "Invalid username and/or password."
return Response(message)

注意:如果我的问题不清楚,请联系我澄清

使用嵌套序列化器:

class CustomerSerializer(ModelSerializer):
class Meta:
model = Customers
fields = '__all__'

class UserSerializer(ModelSerializer):
customers_set = CustomerSerializer(many=True)
class Meta:
model = Users
fields = '__all__'

然后在视图中使用UserSerializer:

...
userializer = UserSerializer(currentUser)

相关内容

  • 没有找到相关文章

最新更新