Django / Python - 在对象创建中使用ManyToMany字段

问题描述 投票:0回答:2

有没有办法使用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表中的特定客户执行此操作? (我会通过电子邮件识别他们)。 (显然不止一个客户)。

非常感谢!

python django django-models
2个回答
3
投票

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

booking = Booking.object.create(tour_ref="ref")
customers = list(Customer.objects.filter(email="[email protected]"))
booking.customers.add(customers)

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

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

0
投票

试试这个,

In [1]: Customer.objects.create(name="name_1",email="[email protected]")
Out[1]: <Customer: Customer object>

In [2]: Customer.objects.create(name="name_2",email="[email protected]")
Out[2]: <Customer: Customer object>

In [3]: Customer.objects.create(name="name_3",email="[email protected]")
Out[3]: <Customer: Customer object>

In [4]: book = Booking.objects.create(tour_ref="reff_1")

In [5]: cus = Customer.objects.filter(email='[email protected]')

In [6]: for c in cus:
   ...:     book.customers.add(c)
   ...:     

In [7]: book.customers.all()
Out[7]: <QuerySet [<Customer: Customer object>, <Customer: Customer object>]>
© www.soinside.com 2019 - 2024. All rights reserved.