How to create an object for a Django model with many to many field?
class Date(models.Model):
date = models.DateField()
def __str__(self):
return str(self.date)
class Time(models.Model):
time = models.TimeField()
def __str__(self):
return str(self.time)
class Showtimes(models.Model):
theater = models.ForeignKey(Theater,on_delete=models.CASCADE,related_name="theater")
movie = models.ForeignKey(Movie,on_delete=models.CASCADE,related_name="movie")
show_date = models.ManyToManyField(Date)
show_time = models.ManyToManyField(Time)
how can i create a objects with multiple date and time by passing aruguments in objects.create function call
Showtimes.objects.create(theater=th,movie=m,show_date = Date.objects.all(),show_time = Time.objects.all()).save()
i want to create a object for ShowTimes by function call objects.create by passing all date and time field
Unfortunately, you can not directly use objects.create()
to set ManyToManyField
relationships, as this function creates the object first and then expects the many-to-many relationships to be added separately.
In Django, ManyToManyField
relationships require you to first create the object without the ManyToMany
fields, then add the related objects afterward using the .set()
or .add()
method.
This is the code example.
showtimes = Showtimes.objects.create(theater=th, movie=m)
showtimes.show_date.set(Date.objects.all()) # or pass specific Date objects
showtimes.show_time.set(Time.objects.all()) # or pass specific Time objects
I hope this will help you a little.
I want to create a object for
ShowTimes
by function callobjects.create
by passing all date and time field.
That is not how .create(…)
[Django-doc] works. In order to populate the ManyToManyField
s, you first need to have a primary key, and thus make a Showtimes
object.
You can first create the item, and then populate the fields:
showtime = Showtimes.objects.create(theater=th, movie=m)
showtime.show_date.set(*Date.objects.all())
showtime.show_time.set(*Time.objects.all())
Strictly speaking, one could probably let .create(..)
populate these fields, but this makes not much sense because the operation would require multiple queries, so if one of these queries fails, the database is in a partial state between "not created" and "created", and it would also make the .create(…)
method a lot more complicated.
Note: Since a
ManyToManyField
refers to a collection of elements,ManyToManyField
s are normally given a plural name. You thus might want to consider renamingtoshow_date
show_dates
.