Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter django queryset by onetoone model field property

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)
like image 380
Aurora Avatar asked Sep 01 '25 16:09

Aurora


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.

like image 70
cupid22 Avatar answered Sep 04 '25 07:09

cupid22


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

like image 40
Nduati Avatar answered Sep 04 '25 05:09

Nduati