Django,ForeignKey到非唯一字段?

时间:2017-01-24 13:18:48

标签: django django-models

我想要一个参考字段(通常是一个外键字段)

parent字段是参考字段。

以下是显示我正在尝试做的简化模型。 对于给定的类Foo,我想创建另一个可以容纳Foo副本的类FooCopy。

(FooCopy.id,FooCopy.user_edit)对是唯一的。

class Foo(Base):

    parent = models.ForeignKey(
        'self',
        null=True, blank=True
    )


class FooCopy(models.Model):
    _id = models.AutoField(primary_key=True)
    id = models.IntegerField(blank=True, null=True, db_index=True)
    user_edit = models.ForeignKey(settings.AUTH_USER_MODEL)

    parent = models.ForeignKey(
        'self',
        null=True, blank=True,
        to_field='id',
        db_constraint=False,
    )


foo = Foo.objects.create()


foo_data = model_to_dict(foo)

foo_copy1 = Foo.objects.create(user_edit=user1, **foo_data)
foo_copy2 = Foo.objects.create(user_edit=user2, **foo_data)


def model_to_dict(obj, exclude=[]):

    data = {}
    for f in obj.__class__._meta.get_fields():
        if f.name in exclude:
            continue
        if f.one_to_many:
            continue

        if isinstance(f, ForeignKey):
            field_name = "{}_id".format(f.name)
        else:
            field_name = f.name
        data[field_name] = getattr(obj, field_name)

    return data

我收到一个错误,说Foo.id需要是唯一的。

(FooCopy.id必须设置unique = True,因为它是由外键引用的。)

我是否可以使用关系字段来引用另一个没有上述限制的django模型实例? (或者我能以某种方式逃脱它吗?)

我只需要能够使用foofoo_id,我不需要ForeignKey的参照完整性。

- 编辑

读完丹尼尔罗斯曼的评论后,我想我可以

parent_id = models.IntegerField()

@property
def parent(self):
  return  self._default_manager.get(id=parent_id, user_edit=self.user_edit)

虽然我可能会遗漏django为外键提供的一些内容,例如parent__name等,但我不确定是否有更好的方法可以做到这一点。

0 个答案:

没有答案