本文介绍了Django多对多型号DRF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下模型结构:
class Project(models.Model):
author = models。 ManyToManyField(Account)
name = models.CharField(max_length = 40,default ='NewBook')
class Account(AbstractBaseUser):
email = models.EmailField(unique =真的)
username = models.CharField(max_length = 40,unique = True)
first_name = models.CharField(max_length = 40,blank = True)
last_name = models.CharField(max_length = 40,blank = True)
tagline = models.CharField(max_length = 140,blank = True)
is_admin = models.BooleanField(default = False)
created_at = models.DateTimeField(auto_now_add =
updated_at = models.DateTimeField(auto_now = True)
objects = AccountManager()
USERNAME_FIELD ='email'
REQUIRED_FIELDS = ['username']
我的看法如下:
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.object s.order_by(' - name')
serializer_class = ProjectSerializer
def perform_create(self,serializer):
instance = serializer.save(author = self.request.user)
return super(ProjectViewSet,self).perform_create(serializer)
调用视图函数在数据库中创建一个分类器。但是之后,我收到以下错误:
错误在此行中抛出:
instance = serializer。保存(author = self.request.user)
任何人都可以帮助我吗? >
解决方案
这里有两个问题:
- 显示M2M领域的:
所以你需要添加许多= True
到 AccountSerializer
:
author = AccountSerializer(read_only = True,required = False,many =
- A :
- Showing nested relationships for M2M field:
所以,如果你看这个例子和文档似乎需要实现创建
或更新
方法。
I have the following model structure:
class Project(models.Model):
author = models.ManyToManyField(Account)
name = models.CharField(max_length=40, default='NewBook')
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True)
first_name = models.CharField(max_length=40, blank=True)
last_name = models.CharField(max_length=40, blank=True)
tagline = models.CharField(max_length=140, blank=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = AccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
My view looks like this:
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.order_by('-name')
serializer_class = ProjectSerializer
def perform_create(self, serializer):
instance = serializer.save(author=self.request.user)
return super(ProjectViewSet, self).perform_create(serializer)
After calling the view function, a classifier gets created in the database. But after that, I get the following error:
The error gets thrown in this line:
instance = serializer.save(author=self.request.user)
Anyone how can help me with this?
解决方案
There are two problems here:
So you need to add many=True
to AccountSerializer
:
author = AccountSerializer(read_only=True, required=False, many=True)
So if you look at the example and the documentation it seems that you need to implement create
or update
method.
这篇关于Django多对多型号DRF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!