models: ManyToManyRel and ManyToManyFiled

django 得models关系讨论:

版本:1.11.4

选择1.11.x系列得原因是同时支持py2.7 和py3,比较稳定,后期django2.0变化主要在path(目前没有看到,不做讨论)

小白得成长之路:路上遇见得问题或者思考想到得在次记录一下,如有高见请大佬解释一下,有疑问共同讨论进步。

ManyToManyFiled:django源码简单拷贝



class ManyToManyField(RelatedField):

"""

Provide a many-to-many relation by using an intermediary model that

holds two ForeignKey fields pointed at the two sides of the relation.

Unless a ``through`` model was provided, ManyToManyField will use the

create_many_to_many_intermediary_model factory to automatically generate

the intermediary model.

"""

    # Field flags

    many_to_many =True

    many_to_one =False

    one_to_many =False

    one_to_one =False

    rel_class = ManyToManyRel

description = _("Many-to-many relationship")

def __init__(self, to, related_name=None, related_query_name=None,

                limit_choices_to=None, symmetrical=None, through=None,

                through_fields=None, db_constraint=True, db_table=None,

                swappable=True, **kwargs):

try:

to._meta

except AttributeError:

assert isinstance(to, six.string_types), (

"%s(%r) is invalid. First parameter to ManyToManyField must be "

                "either a model, a model name, or the string %r" %

(self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)

)

# Class names must be ASCII in Python 2.x, so we forcibly coerce it

# here to break early if there's a problem.

            to =str(to)


采用中介模式,提供一个多对多得关系,使拥有两个外键字段指向关系的双方,除非提供了一个“through”模式,多对多域将使用create_many_to_many_intermediary_model厂自动生成中介模型。

ManyToManyRel


class ManyToManyRel(ForeignObjectRel):

"""

Used by ManyToManyField to store information about the relation.

``_meta.get_fields()`` returns this class to provide access to the field

flags for the reverse relation.

    """


采用多对多域存储联系信息,``_meta.get_fields()``返回这个类提供的对反向关系的字段标志的访问

个人认为后者是关系的表述,日常调用前者更多,挖个坑有读源码能力了回来填

后者调用很少,大概在官方文档溜了一下,model的关系处,没看到对后者的介绍

你可能感兴趣的:(models: ManyToManyRel and ManyToManyFiled)