im试图将相关集合加载到序列化器中,因此整个集合将作为嵌套字典出现在父序列下。
我目前没有任何错误,但是我的api也根本没有为circuits_subnets返回任何数据。
有什么想法吗? 谢谢
编辑
我添加了一个嵌套的序列化程序,但是api仍然没有显示错误和数据
views.py:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Firefox()
driver.get('url')
driver.find_element_by_xpath("xpath_of_dropdownlist").click()
select_Add = Select(driver.find_element_by_id("Address 1"))
select_Add.select_by_index(0)
serializers.py
class DeviceConnViewSet(viewsets.ReadOnlyModelViewSet):
# sub queries
poll_ip = Subquery(
DeviceCircuitSubnets.objects.filter(device_id=OuterRef(
'id'),subnet__subnet_type__poll=True).values('subnet__subnet')[:1])
mgmt_ip = Subquery(
DeviceCircuitSubnets.objects.filter(device_id=OuterRef(
'id'),subnet__subnet_type__mgmt=True).values('subnet__subnet')[:1])
queryset = Device.objects.all().annotate(
poll_ip=poll_ip,
mgmt_ip=mgmt_ip
) \
.select_related('site','site__site_type','model','model__device_type') \
.prefetch_related('devicecircuitsubnets_set') \
.order_by('site__location')
serializer_class = DeviceConn
API输出示例
class CircuitSubnetsSerializer(serializers.ModelSerializer):
circuit_name = serializers.ReadOnlyField(
source='circuit.name',
)
subnet = serializers.ReadOnlyField(
source='subnet.subnet',
)
subnet_mask = serializers.ReadOnlyField(
source='subnet.mask',
)
subnet_type = serializers.ReadOnlyField(
source='subnet.subnet_type.subnet_type',
)
class Meta:
model = DeviceCircuitSubnets
fields = ('circuit_name', 'subnet','subnet_mask','subnet_type')
class DeviceConn(QueryFieldsMixin, serializers.HyperlinkedModelSerializer):
poll_ip = serializers.ReadOnlyField()
mgmt_ip = serializers.ReadOnlyField()
bgp_as = serializers.ReadOnlyField(
source='site.bgp_as',
)
location = serializers.ReadOnlyField(
source='site.location',
)
site_type = serializers.ReadOnlyField(
source='site.site_type.site_type',
)
device_type = serializers.ReadOnlyField(
source='model.device_type.device_type_plural',
)
circuit_subnets = CircuitSubnetsSerializer(many=True, read_only=True)
class Meta:
model = Device
fields = ('site_id','poll_ip','mgmt_ip','bgp_as','hostname', 'device_type','location','site_type','circuit_subnets')
答案 0 :(得分:1)
在DeviceConn
序列化器上,添加一个字段以表示要序列化的关系:
class DeviceConn(serializers.HyperlinkedRelatedField):
your_related_field = serializers.HyperlinkedRelatedField(many=True,
read_only=True, view_name=my_view)
class Meta:
fields = `__all__` # or add only the fields you want.