使用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"
}
错误
invalid hyperlink - no url match
或
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'))
]
我想要Postinfo.useruid = Userinfo.useruid 但我不知道这个错误 怎么样呢
如果将useruid更改为IntegerField,则可以使用
但 这不是外国人的
答案 0 :(得分:2)
您可以使用标准url
并仅将HyperlinkedRelatedField
用于代表用户to_representation
,为此您可以覆盖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)
方法:
to_representation
如果您不需要将用户表示为usl字符串,只需删除ModelSerializer
方法并使用projectmanagement.plan.Plan%3A(.+?)&u8=1\\" ext:qtip=\\"prod-p1\\">prod-p1</a>
作为基类。