1

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!

James
  • 91
  • 1
  • 2
  • 10
  • This explains some possibilities `https://stackoverflow.com/questions/6996176/how-to-create-an-object-for-a-django-model-with-a-many-to-many-field` – mbieren Mar 01 '18 at 17:11

1 Answers1

4

Use add to add list of customers to new booking:

booking = Booking.object.create(tour_ref="ref")
customers = list(Customer.objects.filter(email="email@mail.com"))
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")
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100