【问题标题】:Can a django model have embed classes?django 模型可以嵌入类吗?
【发布时间】:2011-02-09 18:42:25
【问题描述】:

我想要一个这样的 django 模型:

class Model(models.Model):
 string = models.CharField()
 class ContactDetails:
  phone = models.IntegerField()

这可能吗?我试过谷歌搜索,但它似乎没有回答我的问题

这意味着我在访问时会拥有:

Model().ContactDetails.phone

这样工作:)

【问题讨论】:

    标签: django django-models model


    【解决方案1】:

    它可以有嵌入的类(常见的情况是class Meta),但任何models.*Field 成员都会被忽略。这在 SQL 中没有意义。

    你想要的是多对一:

    class Thing(models.Model): # Don't name this class 'Model'!
        name = models.CharField(max_length=100)
    
    class ContactDetails:
        parent = models.ForeignKey(Thing, related_name="contactDetails")
        phone = models.IntegerField()
    

    然后,访问:

    thing = Thing();
    # ... set up thing ...
    thing.save()
    contact1 = ContactDetails(parent=thing)
    # ... set up contact1 ...
    contact1.save()
    contact2 = ContactDetails(parent=thing)
    # ... set up contact2 ...
    contact2.save()
    # ...
    thing.contactDetails.all()
    # returns a list with contact1 and contact2
    

    或其他。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      相关资源
      最近更新 更多