I'm doing an update_or_create queryset operation, which internally uses the get queryset operation. I've read through the documentation on the update_or_create queryset method but I'm having some difficulty in understanding the parts relating to foreign keys and using objects as kwargs.
Consider an example where I have models Book and Chapter and I do something like this:
book = Book.objects.get(...)
kwargs = {'book': book, 'name': 'Chapter 3'}
defaults = {'text': '...'}
Chapter.objects.update_or_create(defaults=defaults, **kwargs)
Now the kwargs will be used in the 'get' method to check whether that chapter exists. But, since book is an object, how does Django know whether there is a chapter with a "matching" book? Does it check whether all fields of the book object match? Does it check only the unique field? Only the primary key of the book? If I have two books with the same fields but different primary key, could they match? Is it good practice to use an object in the kwargs in this way, or do I risk getting integrity error problems? Thank you.
In Django, queryset provides a method called get_or_create that either returns an objects or creates an object. However, like the get method, get_or_create can throw an exception if the query returns multiple objects.
You get a QuerySet by using your model's Manager . Each model has at least one Manager , and it's called objects by default. Access it directly via the model class, like so: >>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name='Foo', tagline='Bar') >>> b.objects Traceback: ...
The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.
Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects. The select_related method is for ForeignKey and OneToOne fields.
In the context, I am assuming that Chapter
has a FK to Book
.
In that chase, Django will use the field ID or, if you changed the default setup, the primary key from the book instance to match. It is the same as doing:
Chapter.objects.update_or_create(defaults=defaults, book=book.id)
So you have have hundreds of books with the exact same fields except the primary key, django will know how to handle it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With