【问题标题】:Django / Python - Using ManyToMany field In Object CreationDjango / Python - 在对象创建中使用多对多字段
【发布时间】:2018-08-09 19:57:33
【问题描述】:

有没有办法使用 ManyToManyField 在模型中创建对象?

以下是模型:

class Booking(models.Model):
    tour_ref = models.CharField(max_length=30)
    customers = models.ManyToManyField(Customer)

class Customer(models.Model):
    name = models.CharField(max_length=40)
    email = models.EmailField()

任务是创建一个新的 Booking 对象。但是如何使用 Customer 表中的特定客户来执行此操作? (我将通过电子邮件识别它们)。 (显然可能不止一位客户)。

非常感谢!

【问题讨论】:

  • 这解释了一些可能性https://stackoverflow.com/questions/6996176/how-to-create-an-object-for-a-django-model-with-a-many-to-many-field

标签: python django django-models


【解决方案1】:

使用add 将客户列表添加到新预订中:

booking = Booking.object.create(tour_ref="ref")
customers = list(Customer.objects.filter(email="email@mail.com"))
booking.customers.add(customers)

或者您可以使用反向查找 booking_setcreate 向特定客户添加预订:

booking = Booking.object.create(tour_ref="ref")
customer.booking_set.create(tour_ref="ref")

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 2021-04-30
    • 1970-01-01
    • 2017-12-23
    • 2020-06-01
    • 2011-10-23
    • 1970-01-01
    • 2013-11-15
    • 2019-06-13
    相关资源
    最近更新 更多