当前位置: 首页>>代码示例>>Python>>正文


Python related.ManyToManyField类代码示例

本文整理汇总了Python中django.db.models.fields.related.ManyToManyField的典型用法代码示例。如果您正苦于以下问题:Python ManyToManyField类的具体用法?Python ManyToManyField怎么用?Python ManyToManyField使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ManyToManyField类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_m2m

 def test_m2m(self):
     """
     Tests adding/removing M2M fields on models
     """
     # Create the tables
     with connection.schema_editor() as editor:
         editor.create_model(AuthorWithM2M)
         editor.create_model(TagM2MTest)
     # Create an M2M field
     new_field = ManyToManyField("schema.TagM2MTest", related_name="authors")
     new_field.contribute_to_class(AuthorWithM2M, "tags")
     try:
         # Ensure there's no m2m table there
         self.assertRaises(DatabaseError, self.column_classes, new_field.rel.through)
         # Add the field
         with connection.schema_editor() as editor:
             editor.add_field(
                 Author,
                 new_field,
             )
         # Ensure there is now an m2m table there
         columns = self.column_classes(new_field.rel.through)
         self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField")
         # Remove the M2M table again
         with connection.schema_editor() as editor:
             editor.remove_field(
                 Author,
                 new_field,
             )
         # Ensure there's no m2m table there
         self.assertRaises(DatabaseError, self.column_classes, new_field.rel.through)
     finally:
         # Cleanup model states
         AuthorWithM2M._meta.local_many_to_many.remove(new_field)
开发者ID:Hestros,项目名称:django,代码行数:34,代码来源:tests.py

示例2: register

def register(model, field_name = None, m2m = False):
    """
    This registers the model class so it can have followers
    """
    from models import Follow
    if model in registry:
        return
        
    registry.append(model)
    
    related_name = 'follow_%s' % model._meta.module_name
    
    if not field_name:
        field_name = model._meta.module_name
    
    # Create foreignkeys by default - less sql queries for lookups
    if m2m:
        field = ManyToManyField(
            model,
            related_name = related_name,
        )
    else:
        field = ForeignKey(
            model,
            related_name = related_name,
            blank = True,
            null = True,
        )
    
    field.contribute_to_class(Follow, field_name)
    setattr(model, 'followers', followers_for_object)
    
    # We need to keep track of which fields and which kind of fields point where
    model_map[model] = [related_name, field_name, m2m]
开发者ID:DnBHeaven,项目名称:django-follow,代码行数:34,代码来源:util.py

示例3: __init__

 def __init__(self, to, chained_field=None, chained_model_field=None,
              show_all=False, auto_choose=False, view_name=None, **kwargs):
     if isinstance(to, basestring):
         self.app_name, self.model_name = to.split('.')
     else:
         self.app_name = to._meta.app_label
         self.model_name = to._meta.object_name
     self.chain_field = chained_field
     self.model_field = chained_model_field
     self.show_all = show_all
     self.auto_choose = auto_choose
     self.view_name = view_name
     ManyToManyField.__init__(self, to, **kwargs)
开发者ID:rashivkp,项目名称:django-smart-selects,代码行数:13,代码来源:db_fields.py

示例4: __init__

 def __init__(self, to, **kwargs):
     ManyToManyFieldOriginal.__init__(to, **kwargs)
     self.model = None
     self.query_field_name = ''
     self.core_filters = {}
     self.instance = None
     self.symmetrical = None
     self.source_field = None
     self.source_field_name = ''
     self.target_field_name = ''
     self.reverse = None
     self.through = None
     self.prefetch_cache_name = None
     self.related_val = None
开发者ID:TestingCI,项目名称:pylint-django,代码行数:14,代码来源:django_db_models_fields_related.py

示例5: test_m2m_repoint

 def test_m2m_repoint(self):
     """
     Tests repointing M2M fields
     """
     # Create the tables
     with connection.schema_editor() as editor:
         editor.create_model(Author)
         editor.create_model(BookWithM2M)
         editor.create_model(TagM2MTest)
         editor.create_model(UniqueTest)
     # Ensure the M2M exists and points to TagM2MTest
     constraints = connection.introspection.get_constraints(
         connection.cursor(), BookWithM2M._meta.get_field_by_name("tags")[0].rel.through._meta.db_table
     )
     if connection.features.supports_foreign_keys:
         for name, details in constraints.items():
             if details["columns"] == ["tagm2mtest_id"] and details["foreign_key"]:
                 self.assertEqual(details["foreign_key"], ("schema_tagm2mtest", "id"))
                 break
         else:
             self.fail("No FK constraint for tagm2mtest_id found")
     # Repoint the M2M
     new_field = ManyToManyField(UniqueTest)
     new_field.contribute_to_class(BookWithM2M, "uniques")
     try:
         with connection.schema_editor() as editor:
             editor.alter_field(Author, BookWithM2M._meta.get_field_by_name("tags")[0], new_field)
         # Ensure old M2M is gone
         self.assertRaises(
             DatabaseError, self.column_classes, BookWithM2M._meta.get_field_by_name("tags")[0].rel.through
         )
         # Ensure the new M2M exists and points to UniqueTest
         constraints = connection.introspection.get_constraints(
             connection.cursor(), new_field.rel.through._meta.db_table
         )
         if connection.features.supports_foreign_keys:
             for name, details in constraints.items():
                 if details["columns"] == ["uniquetest_id"] and details["foreign_key"]:
                     self.assertEqual(details["foreign_key"], ("schema_uniquetest", "id"))
                     break
             else:
                 self.fail("No FK constraint for uniquetest_id found")
     finally:
         # Cleanup through table separately
         with connection.schema_editor() as editor:
             editor.remove_field(BookWithM2M, BookWithM2M._meta.get_field_by_name("uniques")[0])
         # Cleanup model states
         BookWithM2M._meta.local_many_to_many.remove(new_field)
         del BookWithM2M._meta._m2m_cache
开发者ID:Wilfred,项目名称:django,代码行数:49,代码来源:tests.py

示例6: __init__

    def __init__(self, to, chained_field=None, chained_model_field=None,
                 auto_choose=False, **kwargs):
        """
        examples:

        class Publication(models.Model):
            name = models.CharField(max_length=255)

        class Writer(models.Model):
            name = models.CharField(max_length=255)
            publications = models.ManyToManyField('Publication', blank=True, null=True)

        class Book(models.Model):
            publication = models.ForeignKey(Publication)
            writer = ChainedManyToManyField(
                Writer,
                chained_field="publication",
                chained_model_field="publications",
                )
            name = models.CharField(max_length=255)

        ``chained_field`` is the name of the ForeignKey field referenced by ChainedManyToManyField of the same Model.
        in the examples, chained_field is the name of field publication in Model Book.

        ``chained_model_field`` is the name of the ManyToMany field referenced in the 'to' Model.
        in the examples, chained_model_field is the name of field publications in Model Writer.

        ``auto_choose`` controls whether auto select the choice when there is only one available choice.

        """
        try:
            isbasestring = isinstance(to, basestring)
        except NameError:
            isbasestring = isinstance(to, str)
        if isbasestring:
            self.to_app_name, self.to_model_name = to.split('.')
        else:
            self.to_app_name = to._meta.app_label
            self.to_model_name = to._meta.object_name
        self.chain_field = chained_field
        self.chained_model_field = chained_model_field
        self.auto_choose = auto_choose
        ManyToManyField.__init__(self, to, **kwargs)
开发者ID:DjangoBD,项目名称:django-smart-selects,代码行数:43,代码来源:db_fields.py

示例7: register

def register(model, field_name = None, m2m = False):
    """
    This registers the model class so it can have followers,
    adds a method to the model ``get_followers``,
    returning the followers - 
    a query set of ``:class:auth.models.User`` objects
    """
    if model in registry:
        return
        
    registry.append(model)
    
    related_name = 'follow_%s' % model._meta.module_name
    
    # Create foreignkeys by default - less sql queries for lookups
    if m2m:
        field = ManyToManyField(
            model,
            related_name = related_name,
        )
    else:
        field = ForeignKey(
            model,
            related_name = related_name,
            blank = True,
            null = True,
        )
    
    if not field_name:
        field_name = model._meta.module_name

    from models import Follow
    field.contribute_to_class(Follow, field_name)

    model.add_to_class('get_followers', get_followers_for_object)

    # We need to keep track of which fields and which kind of fields point where
    model_map[model] = [related_name, field_name, m2m]
开发者ID:ASKBOT,项目名称:django-follow,代码行数:38,代码来源:util.py

示例8: __init__

 def __init__(self, translated_field, language, to, *args, **kwargs):
     self._related_pre_init(translated_field, language, *args, **kwargs)
     ManyToManyField.__init__(self, to, **kwargs)
     self._related_post_init()
开发者ID:kellycreativetech,项目名称:django-modeltranslation,代码行数:4,代码来源:fields.py

示例9: __init__

    template = '%(expressions)s'
    arg_joiner = ' - '
    arity = 2

    def __init__(self, start, end):
        super(DateDiff, self).__init__(start, end)

    def as_microsoft(self, compiler, connection):
        self.template = 'cast(DateDiff(day,%(expressions)s) as float)* -1 *24*60*60*1000.0*1000.0' # Convert to microseconds as used by Django DurationField'
        self.arg_joiner = ', '
        return super(DateDiff, self).as_sql(compiler, connection)

    def as_sql(self, compiler, connection, function=None, template=None):
        if connection.vendor is 'microsoft':
            return self.as_microsoft(compiler, connection)
        return super(DateDiff, self).as_sql(compiler, connection)


class NotEqual(Lookup):
    lookup_name = 'ne'

    def as_sql(self, qn, connection):
        lhs, lhs_params = self.process_lhs(qn, connection)
        rhs, rhs_params = self.process_rhs(qn, connection)
        params = lhs_params + rhs_params
        return '%s != %s' % (lhs, rhs), params
Field.register_lookup(NotEqual)
RelatedField.register_lookup(NotEqual)
ForeignObject.register_lookup(NotEqual)
ManyToManyField.register_lookup(NotEqual)
开发者ID:LegoStormtroopr,项目名称:django-data-interrogator,代码行数:30,代码来源:db.py


注:本文中的django.db.models.fields.related.ManyToManyField类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。