【问题标题】:How do I make a model automatically from another model?如何从另一个模型自动制作模型?
【发布时间】:2020-08-11 20:40:30
【问题描述】:

每当用户进行新的预订时,我希望使用预订类中的“first_name”、“last_name”和“email”字段自动创建个人资料。

models.py

from django.db import models
from django.db.models.signals import post_save

class Reservation(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField()
    address = models.CharField(max_length=50)
    check_in = models.DateField()
    check_out = models.DateField()
    num_guest = models.IntegerField()

    reason = (
    ('Birthday', 'Birthday'),
    ('Anniversary', 'Anniversary'),
    ('Get Away From Kids', 'Get Away From Kids'),
    ('Vacation', 'Vacation'),
    ('Treating Myself', 'Treating Myself'),
    ('Leave Blank', 'Leave Blank'),
    )

    opt = models.CharField(max_length=120, choices = reason)

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Profile(models.Model):

    guest = models.ForeignKey(Reservation, on_delete=models.CASCADE)

    def __str__(self):
        return "%s" % (self.guest)

def create_profile(sender, instance, created, **kwargs):
        post_save.connect(create_profile, sender=Reservation)

我试图不修改 Reservation 类,因为我需要将字段作为 ModelForm。

编码新手,感谢您的指导!

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    这就是abstract base classes 的用途,我相信。不过,不确定一致性,但您仍然可以将外键存储到 Reservation。或者,您可以在 Profile 中定义 @property 并手动检索数据(根据这个问题:Django queryset with Model method containing another queryset)。

    【讨论】:

    • 抽象基类“不生成数据库表也没有管理器,不能直接实例化或保存。”这与我需要的相反
    • 不适用于基类本身。您将公共字段放入基类中,并且 Reservation 和 Profile 都应该从它继承。
    猜你喜欢
    • 2019-12-31
    • 2011-09-27
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多