James
James

Reputation: 91

Django / Python - Using ManyToMany field In Object Creation

Is there any way to create an object in a model using a ManyToManyField?

Here are the models:

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()

The task is to create a new Booking object. But how do I do this using specific customers from the Customer table? (I would be identifying them by email). (Obviously more than one customer would be likely).

Many thanks!

Upvotes: 1

Views: 64

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

Use add to add list of customers to new booking:

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

or you can add booking to specific customer using reverse lookup booking_set and create:

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

Upvotes: 4

Related Questions