【问题标题】:How to add data in table dynamically in django?如何在 django 中动态添加表中的数据?
【发布时间】:2020-08-22 06:04:26
【问题描述】:

我的models.py 中有两个模型。

class Book(models.Model):
    book_id = models.AutoField
    book_name = models.CharField(max_length=50)
    book_author = models.CharField(max_length=50)
    book_category = models.CharField(max_length=50)

class Author(models.Model):
    author_id = models.AutoField
    author_name = models.CharField(max_length=50)
    author_description = models.CharField(max_length=500)

我希望每当我在Book 表中添加新行时,它会自动为每个唯一作者在Author 表中输入(只有 author_id 和 author_name,author_description 我将手动添加)。 怎么做?

【问题讨论】:

  • views.py 在哪里处理这个问题?

标签: django database django-models


【解决方案1】:

你可以通过一些不同的方式做到这一点。我建议你通过以下方式:

  1. 覆盖Book 模型的Save 方法。 (使用Save方法)
  2. Signal 发送到Author 模型以创建Author 对象。

现在,我实现第二种方式:

@receiver(post_save, sender=Book)
def create_author(sender, instance, created, **kwargs):
    if created:
        author = Author.objects.create(id=your_id,author_name=your_author_name,author_description=your_author_description)
        Book.objects.objects.filter(pk=instance.id).update(author=author)


@receiver(post_save, sender=Book)
def save_author(sender, instance, **kwargs):
    instance.author.save()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多