如何以编程方式在 ManyToManyField 中创建多个条目

发布于 2024-12-27 08:05:01 字数 693 浏览 2 评论 0原文

恐怕这是个菜鸟问题。我有一个包含多个类的数据库,其中有类图片和页面:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清君侧 2025-01-03 08:05:01

只需在下一条语句中执行即可:

newPage = Page.objects.create(page_uuid="SAMPLE-PAGE-UUID")
newPage.pictures.add(newPic, newPic2, newPic3)

在文档中

Just do it in the next statement:

newPage = Page.objects.create(page_uuid="SAMPLE-PAGE-UUID")
newPage.pictures.add(newPic, newPic2, newPic3)

In the docs

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文