简体   繁体   中英

Validating the type of django queryset related objects parameters

Does django provide a way to validate the model type in django queryset when for example filtering by related objects? Let's say we have the following models:

class Person(models.Model):
    name = models.CharField(max_length=5)

class Author(models.Model):
    name = models.CharField(max_length=25)

class Book(models.Model):
    name = models.CharField(max_length=5)
    author = models.ForeignKey(Author)

And

p = Person.objects.all().first()
query = Book.objects.filter(author=p)

filters all books which auhtor_id is equal to given person_id (p_id), although Book refers to Author, not to Person.

Of course this is the responsibility of a programmer to avoid such errors but it's sitll possible.

This happens in django 1.7

p = Person.objects.all().first()
query = Book.objects.filter(author=p)

Did you actually try this? According to me it should raise a ValueError Something along the lines of 'Must be a Author instance"

Now if you want to avoid this error, you need to use an id, and Moses as usual has a good answer showing how it's done.

如果author_idauthor_id相同, person_id可以直接使用id进行过滤

query = Book.objects.filter(author_id=p.id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM