简体   繁体   English

验证Django queryset相关对象参数的类型

[英]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? 当例如通过相关对象过滤时,django是否提供一种方法来验证django queryset中的模型类型? 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. 过滤auhtor_id等于给定person_id(p_id)的所有书籍,尽管Book指的是作者,而不是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 这在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" 据我说,它应该引发ValueError “必须是Author实例”

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. 现在,如果您想避免此错误,则需要使用一个id,像往常一样,Moses有一个很好的答案来说明它是如何完成的。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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