For example, I have two models in a car management system(webpage):
class Brand(models.Model):
brand_name= models.CharField(max_length=100, null=False)
class Cars(models.Model):
car_model= models.CharField(max_length=100, null=False)
car_production_year= models.CharField(max_length=100, null=False)
car_brand= models.ForeignKey(Brand, null=True, blank=True, default = None)
Now, I want to delete a Brand data from the car system. How can I check if this Brand has been used in another model or does that foreign key contains any data(as I have allowed null True for car_brand in Cars model).
PS: using this function:
self.model._meta.get_all_related_objects():
I got any related object in used in Brand model class. But, I don't know how to get if that related object contains any data.
In Django, a related object is a model instance used in the one-to-many or many-to-many context. For example, let’s look at the built-in User model, which has a many-to-many relationship with the Group model. For any given User object, all linked Group objects are called “related objects”.
Django will complain if you try to assign or add an object of the wrong type. To retrieve objects from your database, construct a QuerySet via a Manager on your model class. A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters.
In the query2 django is joining the foreign key relationships so, when foreign key data is required then django ORM will not hit the database. query1 results in 1 + number of records queries to the database where as in query2 it results in only 1 database query. So, It's recommended to use the select_related when we use foreign key related data.
Once you’ve created your data models, Django automatically gives you a database-abstraction API that lets you create, retrieve, update and delete objects. This document explains how to use this API.
From this question, for my code, this was faster:
for b in Brand.objects.filter(cars__isnull=True):
# delete
If You have the ids (my case), I used this (60% faster than cars_set):
for brand_id in brand_id_set:
if Brand.objects.filter(id=brand_id).filter(cars__isnull=True):
# delete
I am using Django 1.11
Use exists()
. It's designed to be used for exactly this type of situations:
for brand in Brand.objects.all():
if not brand.cars_set.all().exists():
# delete
Also it's almost always faster than any other type of check because of the way it is designed to work at the database level. You can read details of exists()
behaviour in the docs
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