【发布时间】:2023-03-29 07:20:02
【问题描述】:
我尝试构建 API 以将一些对象保存到用户最喜欢的位置。 我有这个用于用户配置文件的类:
class Profile(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(blank=False, null=False, unique=True)
first_name = models.CharField(blank=True, null=True, max_length=255)
last_name = models.CharField(blank=True, null=True, max_length=255)
# some enother fields
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
以及用于配置文件的 sweetpie-API:
class ProfileResource(ModelResource):
class Meta:
queryset = Profile.objects.all()
resource_name = 'profiles'
allowed_methods = ['get', 'patch']
authentication = Authentication()#MultiAuthentication(ApiKeyAuthentication(), SessionAuthentication())
authorization = Authorization()
以及与个人资料相关的对象
class News(models.Model):
title = models.CharField(blank=False, null=False, max_length=255, verbose_name=u'Заголовок')
add_to_favorite=models.ManyToManyField('profiles.Profile', related_query_name='favorite_news', blank=True)
class NewsResource(ModelResource):
add_to_favorite = fields.OneToManyField(
'profiles.api.ProfileResource',
attribute='add_to_favorite',
full=False, blank=True, null=True)
class Meta:
queryset = News.objects.all()
resource_name = 'news'
allowed_methods = ['get', 'patch']
现在我尝试执行这个请求
{
"id": 1,
"add_to_favorite":[
{"id":3}
]
}
得到了错误:IntegrityError: column email is not unique。
但邮件栏是独一无二的。并且数据库中的所有电子邮件都是唯一的。 如何修复我的模型和资源以解决此问题?
谢谢!
【问题讨论】:
-
你确定有一个 ID 为 3 的配置文件吗?如果不好吃,可能会尝试使用该 ID 和空白电子邮件创建一个新的。
-
另外,我认为你想要一个 ToManyField,而不是 OneToManyField,因为它代表一个 ManyToManyField。它们实际上是同一个类,但语义不同,因此未来的行为可能会有所不同。
-
您能发布 IntegriyError 的回溯吗?