如何以编程方式在 ManyToManyField 中创建多个条目
恐怕这是个菜鸟问题。我有一个包含多个类的数据库,其中有类图片和页面:
class Picture(models.Model):
picture_uuid = models.CharField(max_length=36)
class Page(models.Model):
page_uuid = models.CharField(max_length=36)
pictures = models.ManyToManyField(Picture)
在我的数据库中创建新图片条目很简单:
newPic = Picture.objects.create(picture_uuid="SAMPLE-UUID")
newPic2 = Picture.objects.create(picture_uuid="SAMPLE2-UUID")
newPic3 = Picture.objects.create(picture_uuid="SAMPLE3-UUID")
等等。
但是,我不知道如何将这些图片添加到某个页面:
newPage = Page.objects.create(page_uuid="SAMPLE-PAGE-UUID", pictures= … )
如果我想怎么办以编程方式实现这一点,即将我的三张图片添加到这个新页面?
A noob question, I'm afraid. I have a database with several classes, among them the class picture and page:
class Picture(models.Model):
picture_uuid = models.CharField(max_length=36)
class Page(models.Model):
page_uuid = models.CharField(max_length=36)
pictures = models.ManyToManyField(Picture)
Creating new pictures entries in my database is straight forward:
newPic = Picture.objects.create(picture_uuid="SAMPLE-UUID")
newPic2 = Picture.objects.create(picture_uuid="SAMPLE2-UUID")
newPic3 = Picture.objects.create(picture_uuid="SAMPLE3-UUID")
etc.
However, I have no idea how to add these pictures to a certain page:
newPage = Page.objects.create(page_uuid="SAMPLE-PAGE-UUID", pictures= … )
What if I wanted to achieve this programatically, i.e. adding my three pictures to this newPage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在下一条语句中执行即可:
在文档中
Just do it in the next statement:
In the docs