Eleena
Eleena

Reputation: 99

Django Models compare 2 model and filter

i want to get the model details with corresponding another model

my models.py

class Device(models.Model):
    DeviceName = models.CharField(max_length=50, null=True, default=None, blank=True)
    Camera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='CameraId')

    class Meta:
        db_table = "Device"

class Camera(models.Model):
    CameraId = models.AutoField(primary_key=True, db_column='CameraId')
    CameraName = models.CharField(max_length=50)

    class Meta:
        db_table = "Camera"

i want my camera details

that is the camera details that not saved in Device foreign key (means the camera details that not used the foreign key for device)

Upvotes: 0

Views: 32

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

You can check for the Camera objects where the related model (here device) is None/NULL:

Camera.objects.filter(device=None)

This wokrs because Django will make a LEFT OUTER JOIN, so in case there is no device present, it will add one row with NULL as value for the columns related to the Device.

Upvotes: 1

JPG
JPG

Reputation: 88569

Try to use device__isnull=True filter (Ref: Django isnull lookup)

camera_without_devices = Camera.objects.filter(device__isnull=True)

Upvotes: 2

Related Questions