Django M2M通过具有多个模型的额外字段 [英] Django M2M Through extra fields with multiple models

查看:187
本文介绍了Django M2M通过具有多个模型的额外字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出建立以下django模型(出于安全原因而通用)的最佳方法.

I'm trying to figure out the best way to set up the following django model (genericised for security reasons).

ThingA:
    User(M2M through "UserRelation")

ThingB:
    User(M2M through "UserRelation")

ThingC:
    User(M2M through "UserRelation")

User:
    Login_name

UserRelation:
    User (foreginkey)
    Thing (foreignkey) #is this generic to any of the above "things"
    Privilege

我知道在两个不同的模型之间使用直通",但是我不确定如何将其应用于多个模型.我将为UserRelation模型中的每个"Thing"模型定义一个外键吗?

I understand using "through" between two distinct models, but I'm not sure how to apply this to multiple models. Would I define a foreignkey for each of the "Thing" models in my UserRelation Model?

推荐答案

您似乎正在尝试建立通用的多对多关系.有一个专用的django应用可用于此目的: django-gm2m

It looks like you are trying to setup a generic many-to-many relationship. There is a dedicated django app that you can be use for this purpose: django-gm2m

以下是在一般情况下如何使用它的方法:

Here is how to use it in your generic case:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey

from gm2m import GM2MField


class ThingA(models.Model):
    pass

class ThingB(models.Model):
    pass

class ThingC(models.Model):
    pass

class User(models.Model):
     login_name = models.CharField(max_length=255)
     things = GM2MField(through='UserRelation')

class UserRelation(models.Model):
     user = models.ForeignKey(User)
     thing = GenericForeignKey(ct_field='thing_ct', fk_field='thing_fk')
     thing_ct = models.ForeignKey(ContentType)
     thing_fk = models.CharField(max_length=255)

     privilege = models.CharField(max_length=1)

您现在可以访问给定用户的所有things和给定'事物'的所有User实例,以及每个UserRelation实例的特权属性.

You can now access all the things for a given user and all the User instances for a given 'thing', as well as the privilege attribute for each UserRelation instance.

这还将为您提供一些可能需要的好处(反向关系,预取等). GM2MField的行为基本上与django ManyToManyField一样.

This will additionally provide you with a handful of benefits (reverse relations, prefetching, etc.) you may need. A GM2MField basically behaves exactly like a django ManyToManyField.

免责声明:我是 django-gm2m

这篇关于Django M2M通过具有多个模型的额外字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆