django 将ManyToMany字段从一个模型示例复制到另一个

fafcakar  于 2023-05-01  发布在  Go
关注(0)|答案(2)|浏览(107)

我是django的新手,作为一个学习应用,我正在构建一个费用记录应用。
在我的模型中,我有三个类,看起来像这样(为了简洁,我稍微简化了它们):

class AbstractExpense(models.Model):
    description = models.CharField(max_length=100)
    amount      = models.IntegerField()
    category    = models.ForeignKey('Category')
    tags        = models.ManyToManyField('Tag')
    insert_date = models.DateTimeField(auto_now=True)

    class Meta(object):
        abstract = True

class Expense(AbstractExpense):
    date        = models.DateField('Date')

class RecurringExpense(AbstractExpense):
    FREQUENCY_CHOICES = (('D', 'daily'),
                         ('W', 'weekly'),
                         ('M', 'monthly'),
                         ('Y', 'yearly'))
    start_date = models.DateField(blank=False)
    end_date = models.DateField(blank=True, null=True)
    last_check = models.DateField(blank=True, null=True)
    frequency = models.CharField(blank=False, max_length=1, choices=FREQUENCY_CHOICES)

RecurringExpense只是一个模板:当系统意识到插入经常性费用的时间(例如,例如:租金)它应该获取模板中的信息并将其复制到Expense类的新示例中。下面是负责这项工作的RecurringExpense方法的相关部分:

Expense(description=self.description,
        amount=self.amount,
        category=self.category,
        # tags=self.tags,
        date=expense_date).save()

上面的工作是完美的,但是如果我取消注解tags=self.tags行,django会抱怨并抛出以下错误:

Exception Type: TypeError
Exception Value: 'tags' is an invalid keyword argument for this function
Exception Location: <snip>/django/db/models/base.py in __init__, line 367

我知道I could create a loop可以解决这个问题,但我想知道是否有一种更优雅的方法可以让我立即执行相同的操作。...

pcww981p

pcww981p1#

不能像创建模型示例时那样直接设置m2m字段。请尝试以下操作:

expense = Expense(description=self.description,
        amount=self.amount,
        category=self.category,
        date=expense_date)
expense.save()
expense.tags.add(*self.tags.all())

您可以查看https://docs.djangoproject.com/en/1.4/topics/db/examples/many_to_many/以获取更多有关如何处理多对多关系的示例。

eufgjt7s

eufgjt7s2#

我能想到的最简单的方法是:

e = Expense(description=self.description,
            amount=self.amount,
            category=self.category,
            date=expense_date)
e.save()
e.tags = self.tags.all()

相关问题