英文:
How to declare user_id on ModelViewSet in DjangoRestFramework
问题
Foreignkey root is User > Comparelist > obj
我不知道我的代码有什么问题。错误消息告诉我需要 user_id 的 comparelist。
accounts > models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from .managers import UserManager
from core.models import TimestampedModel
class User(AbstractBaseUser, PermissionsMixin, TimestampedModel):
email = models.EmailField(max_length=30, unique=True, null=False, blank=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
USERNAME_FIELD = 'email'
accounts > serializers.py
from .models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
def create(self, validated_data):
user = User.objects.create_user(
email=validated_data['email'],
password=validated_data['password']
)
return user
ImageConverters > models.py
from django.db import models
from accounts.models import User
class CompareList(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner")
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(auto_now_add=True)
class Obj(models.Model):
comparelist = models.ForeignKey(CompareList, on_delete=models.CASCADE)
object_name = models.CharField(max_length=100)
image = models.URLField(max_length=500)
ImageConverters > serializers.py
from .models import CompareList, Obj
from rest_framework import serializers
class ObjSerializer(serializers.ModelSerializer):
class Meta:
model = Obj
fields = ['object_name', 'image']
class CompareListSerializer(serializers.ModelSerializer):
objs = ObjSerializer(many=True, read_only=True)
class Meta:
model = CompareList
fields = ['id', 'objs']
def create(self, validated_data):
images_data = self.context['request'].FILES
texts_data = self.context['request'].data
comparelist = CompareList.objects.create(**validated_data)
for image_data, text_data in zip(images_data.getlist('image'), texts_data.getlist('object_name')):
Obj.objects.create(comparelist=comparelist, image=image_data, object_name=text_data)
return comparelist
ImageConverters > views.py
from rest_framework.viewsets import ModelViewSet
from .models import CompareList, Obj
from .serializers import CompareListSerializer, ObjSerializer
class CompareListCreate(ModelViewSet):
queryset = CompareList.objects.all()
serializer_class = CompareListSerializer
class ObjListCreate(ModelViewSet):
queryset = Obj.objects.all()
serializer_class = ObjSerializer
我向服务器发送了 POST 请求,但我收到了错误消息。
英文:
Foreignkey root is
User> Comparelist > obj
I don't know what's wrong with my code.
Error message said me comparelist required user_id
accounts> models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from .managers import UserManager
from core.models import TimestampedModel
class User(AbstractBaseUser, PermissionsMixin, TimestampedModel):
email = models.EmailField(max_length=30, unique=True, null=False, blank=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
USERNAME_FIELD = 'email'
accounts> serializers.py
from .models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
def create(self, validated_data):
user = User.objects.create_user(
email = validated_data['email'],
password = validated_data['password']
)
return user
ImageConverters> models.py
from django.db import models
from accounts.models import User
class CompareList(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner")
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(auto_now_add=True)
class Obj(models.Model):
comparelist = models.ForeignKey(CompareList, on_delete=models.CASCADE)
object_name = models.CharField(max_length=100)
image = models.URLField(max_length=500)
ImageConverters> serializers.py
from .models import CompareList, Obj
from rest_framework import serializers
class ObjSerializer(serializers.ModelSerializer):
class Meta:
model = Obj
fields = ['object_name', 'image']
class CompareListSerializer(serializers.ModelSerializer):
objs = ObjSerializer(many=True, read_only=True)
class Meta:
model = CompareList
fields = ['id', 'objs']
def create(self, validated_data):
# print(dir(self))
print(self)
print('------------------')
images_data = self.context['request'].FILES
texts_data = self.context['request'].data
comparelist = CompareList.objects.create(**validated_data)
print(texts_data)
for image_data, text_data in zip(images_data.getlist('image'), texts_data.getlist('object_name')):
print(image_data, text_data)
Obj.objects.create(comparelist=comparelist, image=image_data, object_name=text_data)
return comparelist
ImageConverters> views.py
from rest_framework.viewsets import ModelViewSet
from .models import CompareList, Obj
from .serializers import CompareListSerializer, ObjSerializer
class CompareListCreate(ModelViewSet):
queryset = CompareList.objects.all()
serializer_class = CompareListSerializer
class ObjListCreate(ModelViewSet):
queryset = Obj.objects.all()
serializer_class = ObjSerializer
I sent post to server. But I got Error
答案1
得分: 1
你正在尝试创建一个没有用户字段的CompareList对象。这违反了数据库关系,因为用户是必需的才能创建CompareList对象。
如果经过身份验证的用户是CompareList对象的所有者(假设只有授权用户才能执行此操作),请将您的序列化器创建方法更新如下:
def create(self, validated_data):
# print(dir(self))
print(self)
print('------------------')
images_data = self.context['request'].FILES
texts_data = self.context['request'].data
comparelist = CompareList.objects.create(**validated_data, user=self.context['request'].user)
print(texts_data)
for image_data, text_data in zip(images_data.getlist('image'), texts_data.getlist('object_name')):
print(image_data, text_data)
Obj.objects.create(comparelist=comparelist, image=image_data, object_name=text_data)
return comparelist
英文:
You are trying to create a CompareList object without user field. Which violate with database relationship since user is required to create CompareList object.
If authenticated user is the owner of a CompareList object(Assuming only authorized user should be authorized to perform this action). update your serializer create method like this:
def create(self, validated_data):
# print(dir(self))
print(self)
print('------------------')
images_data = self.context['request'].FILES
texts_data = self.context['request'].data
comparelist = CompareList.objects.create(**validated_data, user=self.context['request'].user)
print(texts_data)
for image_data, text_data in zip(images_data.getlist('image'), texts_data.getlist('object_name')):
print(image_data, text_data)
Obj.objects.create(comparelist=comparelist, image=image_data, object_name=text_data)
return comparelist
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论