返回多对多关系中的代理类,Django 2.0
从另一个安装的应用程序,我有这样的模型返回多对多关系中的代理类,Django 2.0,django,django-models,django-2.0,Django,Django Models,Django 2.0,从另一个安装的应用程序,我有这样的模型 class Organization(model.Model): name = models.CharField(max_length=255, blank=True) class Person(model.Model): name = models.CharField(max_length=255, blank=True) class Membership(model.Model): organization = model
class Organization(model.Model):
name = models.CharField(max_length=255, blank=True)
class Person(model.Model):
name = models.CharField(max_length=255, blank=True)
class Membership(model.Model):
organization = models.ForeignKey(
Organization,
related_name='memberships',
# memberships will go away if the org does
on_delete=models.CASCADE,
help_text="A link to the Organization in which the Person is a member.")
person = models.ForeignKey(
Person,
related_name='memberships',
null=True,
# Membership will just unlink if the person goes away
on_delete=models.SET_NULL,
help_text="A link to the Person that is a member of the Organization.")
在我的应用程序中,我需要为一些模型添加一些方法。所以我有一个这样的模型
class ProxiedOrganization(other_app.models.Organization):
class Meta:
proxy = True
special_attribute = 'foo'
class ProxiedPerson(other_app.models.Person):
class Meta:
proxy = True
def special_method(self):
print('I do something special')
当我从一个组织获得会员资格时,他们的类型是other\u app.models.Person
> type(proxied_org_instance.memberships[0].person)
<class 'other_app.models.Person'>
>类型(代理组织实例。成员身份[0]。个人)
但是,我希望它们成为我的代理类的实例
> type(proxied_org_instance.memberships[0].person)
<class 'my_app.models.ProxiedPerson'>
>类型(代理组织实例。成员身份[0]。个人)
有什么好办法吗?这是我可以用查询管理器做的事情吗?该解决方案必须适用于Django 2.0。您需要在
组织
中为代理人员
添加外键。例如:
class MemberShip(models.Model):
person = models.ForeignKey(
ProxyPerson,
related_name='memberships',
null=True,
# Membership will just unlink if the person goes away
on_delete=models.SET_NULL,
help_text="A link to the Person that is a member of the Organization.")
或者,您可以通过以下方式获取代理人员实例:
proxy_person = ProxyPerson.objects.get(pk=proxied_org_instance.memberships[0].person.pk)
或
依照
MyPerson类在与其父类相同的数据库表上操作
个人类。特别是,任何新的Person实例也将
可通过MyPerson访问,反之亦然
意味着您可以通过
ProxyPerson
实例访问Person
实例,反之亦然。我改编了Matt Schinckel的,用于使用Django 2.0和2.1的解决方案。代码可以作为。这很有帮助,但我希望将proxied\u org\u实例的行为更改为。默认情况下,成员身份为haveProxiedPerson
在进行查询后不必将其强制转换为ProxiedPerson
。嗯。。但是,我想使用other_app
的Membership
表中的数据。也许我可以通过在my_app
中创建一个非托管Membership
模型来实现这一点,这与类似,但建议的解决方案都不适用于Django 2.0
proxy_persons = ProxyPerson.objects.filter(
pk__in = proxied_org_instance.memberships.all().values_list('person_id')
)