Can't find Django Shell command to purge records from one table, where matching records DON'T exist in another table

I have two tables, and I’m trying to delete all records in one table, where no matching records exist in the matching table.

I’m using the Django Shell to test, but can’t figure the command to say (in plain English)…

>>>Delete/Show all records in my movie table where there are no ratings for it in the ratings table

The Movie table (obviously) has an id field, and the Rating table has a matching FK movie_id field)

The tables are:

class Movie(models.Model):
    imdbID = models.TextField(unique=True)
    title = models.TextField()
    year = models.TextField()

class Rating(models.Model):
    movie = models.ForeignKey(Movie,on_delete=CASCADE)
    user = models.ForeignKey(User,on_delete=CASCADE)  
    rating = models.IntegerField()

A few of the Django commands I have ran are (to try to geet close):

>>> Movie.objects.all()                      ;gives all movies
>>> Rating.objects.all()                     ;gives all ratings
>>> Rating.objects.filter(movie__year=2018)  ;works

But when i try to dig deeper:
(trying to ask for movies where movie_id equals rating movie_id), i get stuck…

>>> Movie.objects.filter(movie_id=rating__movie)

Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘rating__movie’ is not defined

>>> Movie.objects.filter(rating__movie=movie_id)

Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘movie_id’ is not defined

I really want the NOT "WHERE’ condition, but I can’t even get the TRUE condition

You’re looking for the case where the related objects are null.
e.g.
Movie.objects.filter(rating__isnull=True)

1 Like

Thanks Ken!
(Is there anything you don’t know?)
Is there any course/tutorial that covers this kind of stuff?
I wouldn’t have looked toward a null value somewhere, (still don’t quite get it)

On another note, just wondering how this is best / normally handled…
I also posed this question on StackOverflow, and wrong answer there…
Would you answer it there?
‘’’

/fj

There are lots of things I don’t know. I certainly didn’t figure this one out myself - someone taught it to me. (Don’t know where I picked it up from, that was too long ago.)

I have nothing to do with SO.