【发布时间】:2021-05-04 13:30:06
【问题描述】:
++更新了服务器错误的屏幕截图++
我正在尝试设置一个可以清除的 rest API,然后通过端点重新播种我的 postgres db 中的数据。我正在使用带有 json 数据的 Django 执行此操作,并在我的视图中执行一系列函数。到目前为止效果很好,但现在我正在尝试使用外键字段添加数据。
models.py:
class Profile(models.Model):
name = models.CharField(max_length = 100)
profile_name = models.CharField(max_length = 100)
email = models.CharField(max_length = 100)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length = 250)
body = models.TextField(max_length = 4000)
profile = models.ForeignKey(Profile, on_delete = models.CASCADE)
def __str__(self):
return self.title
class Comment(models.Model):
title = models.CharField(max_length = 200)
body = models.TextField(max_length = 1000)
profile = models.ForeignKey(Profile, on_delete = models.CASCADE)
post = models.ForeignKey(Post, on_delete = models.CASCADE)
def __str__(self):
return self.title
在views.py中
def seed(request):
Profile.objects.all().delete()
reset(Profile)
for profile in all_profiles:
add_profile(profile)
Post.objects.all().delete()
reset(Post)
for post in all_posts:
add_post(post)
Comment.objects.all().delete()
reset(Comment)
for comment in all_comments:
add_comment(comment)
return HttpResponse('database cleared and seeded')
def add_profile(new_profile):
profile_instance = Profile.objects.create(**new_profile)
profile_instance.save()
def add_post(new_post):
post_instance = Post.objects.create(**new_post)
post_instance.save()
def add_comment(new_comment):
comment_instance = Comment.objects.create(**new_comment)
comment_instance.save()
def reset(table):
sequence_sql = connection.ops.sequence_reset_sql(no_style(), [table])
with connection.cursor() as cursor:
for sql in sequence_sql:
cursor.execute(sql)
一些示例种子对象:
all_profiles = [
{
"name": "Robert Fitzgerald Diggs",
"profile_name": "RZA",
"email": "abbotofthewu@wutang.com"
}
]
all_posts = [
{
"title": "Bring da Ruckus",
"body": "some text",
"profile": 5
}
]
all_comments = [
{
"title": "famous dart",
"body": "Ghostface catch the blast of a hype verse My Glock burst",
"profile": 6,
"post": 1
}
]
现在,当我到达端点时,我收到类似“ValueError:无法分配“5”:“Post.profile”必须是“Profile”实例的错误。”我假设这意味着在这种情况下整数“5”只是一个数字,不被视为对任何事物的引用,但我不知道该怎么做。我认为创建模型实例会解决这个问题。
这是我的 CLI 错误: screenshot of server error
有什么想法吗?
【问题讨论】:
标签: django postgresql django-models seeding