使用子继承类的ForeignKey
我想要一个模型接受来自抽象基类的子类。是否可以?最好的方法是什么?
class BaseClass(models.Model): class Meta: abstract = True class A(BaseClass): ... class B(BaseClass): ... class C(BaseClass): ... class Test(models.Model): base = models.ForeignKey(BaseClass) test_inst = Test.objects.get(something=something) b_inst = B.objects.create() test_inst.base = b_inst test_inst.save()
另外,如果上述可以的话。那么是否可以知道该类是什么类型呢?在此示例中,类 Test 中的基类必须知道它属于 B 类。
I want a model to accept child classes from a base, abstract class. Is it possible? Best way to do it?
class BaseClass(models.Model): class Meta: abstract = True class A(BaseClass): ... class B(BaseClass): ... class C(BaseClass): ... class Test(models.Model): base = models.ForeignKey(BaseClass) test_inst = Test.objects.get(something=something) b_inst = B.objects.create() test_inst.base = b_inst test_inst.save()
Also, if the above is possible. Is it then possible to know what type the class was? In this example, the base in the class Test would have to know it's of class B.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
抽象类没有后备存储,这意味着它没有 PK,这意味着您无法与它建立关系。请改用通用外键。
An abstract class has no backing store, which means that it does not have a PK, which means that you cannot have a relation to it. Use a generic foreign key instead.