filter django queryset by onetoone model field property

Viewed 602

i have two model classes and they are related by OneToOneField like here

class Book(models.Model):
      is_user_ok = models.BooleanFiled()
class Mybook(models.Model):
      book = models.OneToOneField( Book, related_name="Book", null=True, blank=True, on_delete=models.SET_NULL)

now i want make a queryset filter by book field property. but here book.is_user_ok cannot be used. how can i make this queryset filter?

queryset = Mybook.objects.filter(book.is_user_ok=True)
2 Answers

You are looking a common problem, what you really want to do is related_name__column_name in filter, in your case you can try

queryset = Mybook.objects.filter(book__is_user_ok=True=True)

Reference from official docs: https://docs.djangoproject.com/en/4.0/topics/db/queries/

double underscore is used for joins as you have already set the relationship in model variety of joins work here, it is used as per the model relation.

You are using a wrong syntax. Replace (book.is_user_ok=True) with (book__is_user_ok=True) The problem is, using '.' instead of '__'. Thats the correct syntax when dealing with another model class

Related