Django/Python-在对象创建中使用多个字段
是否有任何方法可以使用ManyToManyField在模型中创建对象 以下是模型:Django/Python-在对象创建中使用多个字段,python,django,django-models,Python,Django,Django Models,是否有任何方法可以使用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
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()
任务是创建一个新的预订对象。但是如何使用Customer表中的特定客户来实现这一点?(我会通过电子邮件确认他们的身份)。(显然,可能会有多个客户)
非常感谢 使用
add
将客户列表添加到新预订:
booking = Booking.object.create(tour_ref="ref")
customers = list(Customer.objects.filter(email="email@mail.com"))
booking.customers.add(customers)
或者,您可以使用反向查找booking\u set
和create
向特定客户添加预订:
booking = Booking.object.create(tour_ref="ref")
customer.booking_set.create(tour_ref="ref")
使用
add
将客户列表添加到新预订:
booking = Booking.object.create(tour_ref="ref")
customers = list(Customer.objects.filter(email="email@mail.com"))
booking.customers.add(customers)
或者,您可以使用反向查找booking\u set
和create
向特定客户添加预订:
booking = Booking.object.create(tour_ref="ref")
customer.booking_set.create(tour_ref="ref")
这解释了一些可能性
https://stackoverflow.com/questions/6996176/how-to-create-an-object-for-a-django-model-with-a-many-to-many-field
这解释了一些可能性https://stackoverflow.com/questions/6996176/how-to-create-an-object-for-a-django-model-with-a-many-to-many-field