限制子类的外键选择 [英] Restricting ForeignKey choices on sub-classes
问题描述
我有一套模型,关于餐馆和运行他们的厨师 * :
class Chef(models.Model):
name = models.TextField()
class Restaurant(models.Model):
name = models.TextField()
Chef = models.ForeignKey(Chef)
class FrenchChef(Chef):
angryness = models.PositiveIntegerField()
class FrenchRestaurant(Restaurant):
region = models.TextField()
不幸的是,这个当前模型意味着一个非 - code> FrenchChef 可以运行 FrenchRestaurant
。
有没有我可以将子类模型的 ForeignKey
的查询集限制为父类中可用的子集?
*我的造型实际上不是厨师和餐厅,但这更容易解释。这可能不是很明显,但是 c>厨师</ code>和 FrenchChef
确实需要以不同的模式化。 / p>
像我在评论中提到的,你可以看一下django模型数据验证方法。刚刚在这篇文章中发现了另一个注释。
添加自定义Django模型验证
以下是进行验证的常见模式。代码段从提取的帖子中的一个答案中提取出来。由 https://stackoverflow.com/users/247542/cerin 回复
您可以继续阅读django文档中有关验证的更多信息。
如果您正在寻找可能存在的任何类型/基于Inheretance的解决方案。我不知道他们是否可能存在。我仍然想看看有没有人在django中提出这样的条款。
I have a set of models, regarding restaurants and the chefs that run them*:
class Chef(models.Model):
name = models.TextField()
class Restaurant(models.Model):
name = models.TextField()
chef = models.ForeignKey(Chef)
class FrenchChef(Chef):
angryness = models.PositiveIntegerField()
class FrenchRestaurant(Restaurant):
region = models.TextField()
Unfortunately, this current model means a non-FrenchChef
can run a FrenchRestaurant
.
Is there away that I can restrict the queryset for the ForeignKey
of a subbclassed model to be a subset of those available on the parent class?
* My modelling isn't actually chefs and restaurants, but this is easier to explain. It might not seem obvious, but Chef
s and FrenchChef
s do need to be modelled differently.
Like I was mentioning in the comment, You can look at django model data validation methods. Just found another note at this post. Adding Custom Django Model Validation
Below is a common pattern followed to do validation. code snippet is extract from one of the answers in the abouve mentioned post . answered by https://stackoverflow.com/users/247542/cerin
class BaseModel(models.Model):
def clean(self, *args, **kwargs):
# add custom validation here
super(BaseModel, self).clean(*args, **kwargs)
def save(self, *args, **kwargs):
self.full_clean()
super(BaseModel, self).save(*args, **kwargs)
You can go ahead and read more about validation in django documentation.
If you are looking for any type/inheretance based solutions that might exist. I am not sure if they might exist. I would still like to see if someone comes up with such provision in django.
这篇关于限制子类的外键选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!