Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Check for related objects and whether it contains data

Tags:

python

django

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.

like image 267
ruddra Avatar asked Apr 17 '14 06:04

ruddra


People also ask

What is a related object in Django?

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”.

How do I retrieve objects from the database in Django?

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.

What is the difference between query1 and query2 in Django?

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.

What is the database-abstraction API in Django?

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.


2 Answers

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

like image 55
Raphael Fernandes Avatar answered Sep 30 '22 18:09

Raphael Fernandes


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

like image 32
Max Tepkeev Avatar answered Sep 30 '22 17:09

Max Tepkeev