使用HyperlinkedModelSerializer可以使某些字段(ForeignKey字段)不包含url,仅包含id(如果没有detail-view)

时间:2019-06-29 02:15:33

标签: python django django-rest-framework

我正在使用Django rest框架。在序列化程序中,我使用了HyperlinkedModelSerializer,但是有一些具有详细信息视图的外键字段,因此可以将其呈现为url,但是其中一些没有,它给了我以下错误:

Could not resolve URL for hyperlinked relationship using view name "unit-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field

那怎么解决呢?

serializers.py

class MaterialSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Material
        fields = ('id', 'url', 'name', 'location', 'category', 'unit', 'type', 'price',)

views.py

class MaterialViewSet(viewsets.ModelViewSet):
    queryset = Material.objects.all()
    serializer_class = MaterialSerializer

models.py

class Material(models.Model):
    name = models.CharField(max_length=200)
    location = models.ForeignKey(Location, null=True, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, null=True, on_delete=models.CASCADE)
    unit = models.ForeignKey(Unit, null=True, on_delete=models.CASCADE)
    type = models.CharField(choices=TYPE_CHOICES, default='material', max_length=200)
    price = models.FloatField(default=0, blank=True, null=True)

urls.py

router = DefaultRouter()
router.register('users', user_views.UserViewSet, 'users') 
router.register('profiles', profile_views.ProfileViewSet, 'profile') 
router.register('location', LocationViewSet, 'location') 
router.register('category', CategoryViewSet) 
router.register('materials', MaterialViewSet) 
router.register('supplier', SupplierViewSet) 
router.register('transaction', TransactionViewSet) 

urlpatterns = [
     path('v1/', include(router.urls)), 
    ] 

因此在我的API中,我想成为我的外键字段“位置”和“类别”,其中URL和“单位”字段仅是ID

1 个答案:

答案 0 :(得分:0)

您看到的错误Could not resolve URL for hyperlinked relationship using view name "unit-detail".是因为您的MaterialSerializers.py 您将unit用作字段,并且没有单位的网址。

解决方案:

添加新视图UnitViewset

serializers.py

class UnitSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Unit
        fields = "__all__"

views.py

class UnitViewSet(viewsets.ModelViewSet):
    queryset = Unit.objects.all()
    serializer_class = UnitSerializer

urls.py

router.register('units',UnitViewSet)

编辑您的models.py

如果您希望Material模型的Foreignkey字段中有空白值,请添加blank=True

class Material(models.Model):
    name = models.CharField(max_length=200)
    location = models.ForeignKey(Location, null=True,blank=True, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, null=True,blank=True, on_delete=models.CASCADE)
    unit = models.ForeignKey(Unit, null=True,blank=True, on_delete=models.CASCADE)
    type = models.CharField(default='material',blank=True, max_length=200)
    price = models.FloatField(default=0,blank=True,  null=True)