django - 以多对多关系返回代理类,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 = 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_app.models.Person .
> type(proxied_org_instance.memberships[0].person)
<class 'other_app.models.Person'>

但是,我希望它们成为我的代理类的实例
> type(proxied_org_instance.memberships[0].person)
<class 'my_app.models.ProxiedPerson'>

有没有好的方法来做到这一点?这是我可以用查询管理器做的事情吗?该解决方案必须适用于 Django 2.0。

最佳答案

您需要在 Organization 中放置一个外键至 ProxiedPerson .例如:

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)

或者
proxy_persons = ProxyPerson.objects.filter(
                    pk__in = proxied_org_instance.memberships.all().values_list('person_id')
                )

根据 documentation

The MyPerson class operates on the same database table as its parent Person class. In particular, any new instances of Person will also be accessible through MyPerson, and vice-versa



表示您可以访问 Person实例通过 ProxyPerson实例,反之亦然。

关于django - 以多对多关系返回代理类,Django 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464061/

相关文章:

django - 如何在 Django admin 中实现全局隐式过滤器?

python - django.db.utils.IntegrityError : duplicate key value violates unique constraint "core_user_pkey" DETAIL: Key (id)=(23) already exists

Django:验证时忘记/删除了 FileField 的表单字段输入

python - Django 2.0 与关键字参数 uidb64 的 NoReverseMatch

django - Django 2 中的自定义 LoginView

具有特定数据的 Django 装置

Django在两个字段上组合过滤器

python - MySQL AB,HKEY_LOCAL_MACHINE 中的 MySQL Server 5.5 文件夹不存在

django - 在版本控制中使用应用程序代码存储 Django 的好处

python - 将Django项目移植到Python 3和Django 2时的迁移问题