django foreignkey in HyperlinkedModelSerializer what type of value

Using django 2.0.2

python3.4

models.py

class Userinfo(models.Model):

    useruid = models.BigAutoField(db_column='UserUID', primary_key=True)

    username = models.TextField(db_column='Content')

    registerdate = models.DateTimeField(db_column='RegisterDate')

    class Meta:
        managed = False
        db_table = 'userinfo'

class Postinfo(models.Model):

    postuid = models.BigAutoField(db_column='PostUID', primary_key=True)

    useruid = models.ForeignKey(
    Userinfo, db_column='UserUID', on_delete=models.CASCADE)

    content = models.TextField(db_column='Content')

    registerdate = models.DateTimeField(db_column='RegisterDate')

    class Meta:
        managed = False
        db_table = 'postinfo'

serializer.py

class req_AddPostSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Postinfo
        fields = ('useruid',  'content')

views.py

class AddPost(viewsets.ModelViewSet):
    queryset = ''
    serializer_class = req_AddPostSerializer

    def create(self, request, *args, **kwargs):
        serializer = req_AddPostSerializer(
            data=request.data)
        if not serializer.is_valid():
            return Response(serilizer.errors)
        serializer.save()
        return Response("succes")

request.data

{
    "useruid": "1",
    "content": "test"
}

errors

invalid hyperlink - no url match

or

Incorrect type. Expected URL string, received str

url.py

router = routers.DefaultRouter(trailing_slash=False)
router.register(r'AddPost',
                views.AddPost, base_name="AddPost")
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

i want Postinfo.useruid = Userinfo.useruid but i don't know this error how to this

if change useruid to IntegerField it's worked

but this is out of not foreignkey

1 answer

  • answered 2018-05-16 05:33 neverwalkaloner

    You can use standard ModelSerializer and use HyperlinkedRelatedField only for representaion user as url, for this you can override to_representation method:

    class req_AddPostSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.Postinfo
            fields = ('useruid',  'content')
    
        def to_representation(self, instance):
            self.fields['useruid'] = serializers.HyperlinkedRelatedField(view_name='user-detail', read_only=True)
            return super(req_AddPostSerializer, self).to_representation(instance)
    

    If you don't need users to be represented as usl string, just delete to_representation method and use ModelSerializer as base class.