Как создать объект для модели Django с полями "многие ко многим"?

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)

как создать объект с несколькими датами и временем, передавая aruguments в вызове функции objects.create

Showtimes.objects.create(theater=th,movie=m,show_date = Date.objects.all(),show_time = Time.objects.all()).save()

я хочу создать объект для ShowTimes с помощью функции вызов objects.create, передав все поля даты и времени

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 call objects.create by passing all date and time field.

That is not how .create(…) [Django-doc] works. In order to populate the ManyToManyFields, 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, ManyToManyFields are normally given a plural name. You thus might want to consider renaming show_date to show_dates.

Вернуться на верх