4

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)
Aurora
  • 133
  • 11

2 Answers2

2

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.

cupid22
  • 161
  • 7
1

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

Nduati
  • 75
  • 6