【问题标题】:django model help involving m2m and foreignkey涉及 m2m 和外键的 django 模型帮助
【发布时间】:2013-01-03 08:56:29
【问题描述】:

好的,所以这对于其他人来说可能真的很容易解决,但我真的很困惑如何解决这个问题。

首先,我有一个模型 A,它具有多个与特定表具有多对多关系的字段。比如

class A(models.Model):
    field1 = models.ManyToMany('field1Collection')
    field2 = models.ManyToMany(field2Collection')

class field1Collection(models.Model):
    description = models.TextField()

class field2Collection(models.Model):
    description = models.TextFIeld()

无论如何,这就是我想要完成的。我需要编写另一个可以容纳排名系统的模型。例如,我想创建一个我可以定义的记录

我有 x 个等级(例如 3 个):

  1. field1Collection 对象 3
  2. field2Collection 对象 6
  3. field1Collection 对象 2

所以我基本上希望能够从我的 field1Collection 和 field2Collection 表中选择对象并为其分配排名。我尝试使用外键和 m2m 字段来思考方案,但它们都出错了,因为模型需要“提前”知道我需要引用哪个集合集。这很多有意义吗?谁能帮忙?

【问题讨论】:

    标签: python database django models django-orm


    【解决方案1】:

    您可以使用GenericForeignKey 关系解决此问题

    from django.db import models
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.contenttypes import generic
    
    class RankItem(models.Model):
        rank = models.IntegerField()
        content_type = models.ForeignKey(ContentType)
        object_id = models.PositiveIntegerField()
        content_object = generic.GenericForeignKey('content_type', 'object_id')
    
        def __unicode__(self):
            return self.rank
    

    普通的 ForeignKey 只能“指向”另一个模型,这意味着如果 RankItem 模型使用 ForeignKey,它将必须选择一个且只有一个模型来存储标签。 contenttypes 应用程序提供了一种特殊的字段类型,可以解决此问题并允许与任何模型建立关系

    【讨论】:

      【解决方案2】:

      你需要 field1Collection 和 filed2Collection 有一个共同的祖先类,你可以用一个foreignKey 来引用它。请参阅有关继承的 django 文档。

      【讨论】:

      • 你推荐什么样的继承?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 2015-06-09
      • 2023-02-24
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 2020-11-13
      相关资源
      最近更新 更多