型号:
class Company(models.Model):
name = models.CharField(max_length=200, blank=True, default='')
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, related_name='companies')
class Meta:
ordering = ('-created',)
我使用内置的用户模型
串行器
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = ('name', 'created')
class UserSerializer(serializers.ModelSerializer):
companies = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = User
fields = ('id', 'username', 'email', 'first_name', 'last_name', 'date_joined', 'is_staff', 'is_active',
'is_superuser', 'last_login', 'companies')
查看:
@csrf_exempt
def companies_create(request):
if request.method == 'POST':
data = JSONParser().parse(request)
serializer = CompanySerializer(data=data)
print(serializer)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
答案 0 :(得分:1)
@csrf_exempt
def companies_create(request):
user = get_user_from_somewhere()
if request.method == 'POST':
data = JSONParser().parse(request)
serializer = CompanySerializer(data=data)
print(serializer)
if serializer.is_valid():
serializer.save(user=user)
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
答案 1 :(得分:1)
使用django get_user_model ,
from django.contrib.auth import get_user_model
user_model = get_user_model()
@csrf_exempt
def companies_create(request):
user = get_user_from_somewhere()
if request.method == 'POST':
data = JSONParser().parse(request)
serializer = CompanySerializer(data=data)
print(serializer)
if serializer.is_valid():
serializer.save(user=user_model)
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)