本文介绍了Django模型-外键作为主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下2个表

在models.py

In models.py

class Foo(models.Model):

    uuid = models.CharField(_('UUID'), primary_key=True, default=uuid4)

class FooExt(models.Model):

    uuid = models.ForeignKey(Foo, verbose_name=_('UUID'), primary_key=True)
    time = models.DateTimeField(_('Create DateTime'), auto_now_add=True)

基本上,我有 Foo FooExt 。我想要 FooExt 之间的一对一关系。这就是为什么我将 FooExt 的主键设置为 Foo 的外键的原因(不确定这是否正确)

Basically, I have Foo and FooExt. I want a one-to-one relation between FooExt. That's why I set FooExt's primary key to be foreign key into Foo (not sure if this is the right thing to do).

现在我在 Foo 中添加一个条目。是否会自动创建 FooExt 的条目?还是我需要手动将条目添加到 Foo FooExt 中?

Now I add an entry into Foo. Does an entry for FooExt automatically get created? Or do I need to manually add an entry to both Foo and FooExt?

我可以做些什么来获得自动添加功能吗?从概念上讲,这两个表描述的是同一件事,但我只是不想用额外的信息污染 Foo 。因此,如果添加到 Foo 会自动创建相应的 FooExt ,那就太好了。

Is there anything I can do to get the "automatic" add feature? Conceptually, these 2 tables describe the same thing, but I just don't want to pollute Foo with extra information. So it'd be great if an add to Foo automatically creates a corresponding FooExt.

推荐答案


  1. 如果要建立OneToOne关系,请使用 models.OneToOneField 而不是 models.ForeignKey 。使用外键,您将需要在外键中添加 unique = True

  1. If you want an OneToOne relation, then use models.OneToOneField instead of models.ForeignKey. with foreign keys you will need add unique=True in you ForeignKey:



class Foo(models.Model):
    uuid = models.CharField(_('UUID'), primary_key=True, default=uuid4)

class FooExt(models.Model):
    uuid = models.OneToOneField(Foo, verbose_name=_('UUID'), primary_key=True)
    time = models.DateTimeField(_('Create DateTime'), auto_now_add=True)





  1. 否,创建Foo实例时不会创建FooExt的条目,您需要手动将条目添加到Foo和FooExt中。想想在地方和餐馆中,很多地方都可以是餐馆,但并非所有地方都是餐馆。

  1. No, an entry for FooExt don't get created when you create a Foo instance, you need to manually add an entry to both Foo and FooExt. think in Places and Restaurants, many places can be restaurants, but no all the places are restaurants.

如果您喜欢<$ c $中的自动添加功能c> Foo 创建一个 FooExt 实例,然后您可以在其中重载 save 方法 Foo 也会创建并保存 FooExt 实例,如下所示:

if you like an automatic add feature inside Foo that create a FooExt instance, then you can overload the save method inside Foo that create and save FooExt instance too, something like this:



class Foo(models.Model):
....
....
     def save(self, *args, **kwargs):
        super(Foo, self).save(*args, **kwargs)
        foo_ext = FooExt()
        foo_ext.uuid = self
        foo_ext.save()


这篇关于Django模型-外键作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 23:15