[英]Foreign key field not rendering in serializers django
I am trying to show up the foreign key fields name instead of object id but not able to get through it.我试图显示外键字段名称而不是 object id 但无法通过它。 Tried using the related_name and then binding that to the serializer but still no luck,
尝试使用related_name,然后将其绑定到序列化程序但仍然没有运气,
models.py模型.py
class Employee(base_models.BaseDateModel):
"""
DB model to store employee data
"""
name = models.CharField(max_length=50)
level = models.SmallIntegerField(choices=LEVEL_CHOICES, default=L1)
def __str__(self):
return f'{self.name} - {self.get_level_display()}'
class Room(base_models.BaseDateModel):
"""
DB model to store available rooms in the building
"""
name = models.CharField(max_length=15)
def __str__(self):
return f'{self.name}'
class Seat(base_models.BaseDateModel):
"""
DB model to store available seats in a given room
"""
room = models.ForeignKey('seating.Room', on_delete=models.CASCADE)
def __str__(self):
return f'{self.room} - {self.id}'
class EmployeeSeating(base_models.BaseDateModel):
"""
DB model to store the seating details of any employee
"""
name = models.ForeignKey('seating.Employee', on_delete=CASCADE, related_name='emp_name')
room = models.ForeignKey('seating.ROOM', on_delete=CASCADE, related_name='emp_room')
seat = models.ForeignKey('seating.SEAT', on_delete=CASCADE, related_name='emp_seat')
def __str__(self):
return f'{self.name} - {self.room} - {self.seat}'
serializers.py序列化程序.py
class EmployeeSeatingSerializer(serializers.ModelSerializer):
emp_name = serializers.StringRelatedField()
emp_room = serializers.StringRelatedField()
emp_seat = serializers.StringRelatedField()
class Meta:
model = EmployeeSeating
fields = ('id', 'emp_name', 'emp_room', 'emp_seat')
views.py视图.py
def listemp_api(request, pk=None):
"""
Method to return the list of employee in a given room
"""
if request.method == 'GET':
room_id = pk
if room_id:
employee_data = EmployeeSeating.objects.filter(room_id = room_id)
serializer = EmployeeSeatingSerializer(employee_data, many=True)
return Response(serializer.data)
else:
employee_data = EmployeeSeating.objects.all()
print(employee_data)
serializer = EmployeeSeatingSerializer(employee_data, many=True)
return Response(serializer.data)
The result of the queryset using my view is as below使用我的视图查询集的结果如下
[
{
"id": 1
},
{
"id": 2
},
{
"id": 5
}
]
but I want the room, seat and other serialized fields that I added using stringfield but not able to achieve that.但我想要使用 stringfield 添加但无法实现的房间、座位和其他序列化字段。 Using
fields = '__all__'
gives me object number but misses out the additional fields I want ie.使用
fields = '__all__'
给了我 object 编号,但错过了我想要的其他字段,即。 emp_room, emp_name etc emp_room、emp_name 等
Before moving on, I want to explain that the related_name
field is used if you want to access EmployeeSeating
model from Employee
model.在继续之前,我想解释一下,如果您想从
Employee
model 访问EmployeeSeating
related_name
,则使用 related_name 字段。 But, EmployeeSeatingSerializer
is doing the opposite.但是,
EmployeeSeatingSerializer
正在做相反的事情。 Secondly, in the EmployeeSeating
model foreign keys, I think you should consider renaming seating.ROOM
to seating.Room
(if it's not working) and the same for seating.SEAT
.其次,在
EmployeeSeating
model 外键中,我认为您应该考虑将seating.ROOM
重命名为seating.Room
(如果它不起作用),对于seating.SEAT
。 Make sure from django admin panel if foreign keys are linked properly, otherwise, nothing will work.如果外键链接正确,请确保从 django 管理面板,否则将无法正常工作。
Make sure to do makemigrations
and migrate
after making changes in database.确保在对数据库进行更改后进行
makemigrations
和migrate
。
First, just try this on name
field of the serializer.首先,只需在序列化程序的
name
字段上尝试此操作。 Remove other fields.删除其他字段。
Employee
model, say EmployeeSerializer
.Employee
model 创建一个 model 序列化程序,比如EmployeeSerializer
。 Only give the field which you want to show, which in this case is the name
field.name
字段。EmployeeSeatingSerializer
, change emp_name
field to the field which is used to refer to Employee
model, which is name
in this case.EmployeeSeatingSerializer
中,将emp_name
字段更改为用于引用Employee
model 的字段,在本例中为name
。 Do the same for other fields as well.emp_name = serializers.StringRelatedField()
to name = EmployeeSerializer()
. emp_name = serializers.StringRelatedField()
更改为name = EmployeeSerializer()
。 Do the same for other fields. Give this a try.试试这个。
Try this:尝试这个:
class Employee(base_models.BaseDateModel):
"""
DB model to store employee data
"""
name = models.CharField(max_length=50)
level = models.SmallIntegerField(choices=LEVEL_CHOICES, default=L1)
def __str__(self):
return f'{self.name} - {self.get_level_display()}'
class Room(base_models.BaseDateModel):
"""
DB model to store available rooms in the building
"""
name = models.CharField(max_length=15)
def __str__(self):
return f'{self.name}'
class Seat(base_models.BaseDateModel):
"""
DB model to store available seats in a given room
"""
room = models.ForeignKey(Room, on_delete=models.CASCADE)
def __str__(self):
return f'{self.room} - {self.id}'
class EmployeeSeating(base_models.BaseDateModel):
"""
DB model to store the seating details of any employee
"""
name = models.ForeignKey(Employee, on_delete=CASCADE, related_name='emp_name')
room = models.ForeignKey(Room, on_delete=CASCADE, related_name='emp_room')
seat = models.ForeignKey(Seat, on_delete=CASCADE, related_name='emp_seat')
def __str__(self):
return f'{self.name} - {self.room} - {self.seat}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.