2017-07-26 75 views
2

型號:Django的REST - 創建對象與PrimaryKey的

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) 
  • 應如何JSON文件被髮送到服務器(它包括在公司+ USER_ID模型中的所有字段)?
  • 如何在保存視圖前附加用戶對象?

回答

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

使用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) 
相關問題