Diand
Diand

Reputation: 888

Django ORM Query: How to get record that Not Exist in other table

How to achieve this Raw SQL query in Django ORM?: dbfiddle.

So I have 2 table, Table user and payment, i need to get the user_id that not have a record in payment table (see expected result):

Models.py

class User(models.Model):
    nama_lengkap = models.CharField(max_length=50)
    
class Status_Pembayaran(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT, null=True)
    amount = models.DecimalField(max_digits=1000000, decimal_places=2, 

User table:

table user

Payment table:

paument

Result Expected

enter image description here

Upvotes: 0

Views: 1259

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477502

You can filter with:

User.objects.filter(status_pembayaran=None)

or more verbose:

User.objects.filter(status_pembayaran__isnull=True)

Upvotes: 0

Diand
Diand

Reputation: 888

Find the answer here: https://stackoverflow.com/a/14105717/7664493

inner_qs = Payment.objects.all()
results = User.objects.exclude(id__in=inner_qs)

Upvotes: 1

Related Questions