将一个模型复制到另一个模型时如何复制m2m字段

时间:2019-07-04 17:19:18

标签: django django-signals

我能够使用post_save信号复制除m2m字段之外的模型的所有属性。使用与Shell中相同的步骤时,QuerySet返回空值,因此我无法将字段添加到新对象/模型中。

signals.py

@receiver(post_save, sender=RecurringEventItem)
def create_calendar_event(sender, instance, created, **kwargs):
    if created:
        min_date = datetime.now() - timedelta(days=365)
        max_date = datetime.now() + timedelta(days=365)
        recurring_event = RecurringEventItem.objects.get(pk=instance.id)
        print(recurring_event.attendee)
        print(recurring_event.attendee.all())
        if recurring_event.attendee is not None:
            attendees = recurring_event.attendee.all()

        if instance.recurrences is not None:
            calendar_item_list = []
            recurrence_dates = list(instance.recurrences.between(min_date, max_date))
            for date in recurrence_dates:
                new_calendar_item = CalendarItem(name=instance.name, start_date=instance.start_date,
                                                 completion_date=instance.completion_date,
                                                 description=instance.description,
                                                 end_date=datetime.date(date))
                if attendees:
                    new_calendar_item.calendar_attendees.add(attendees)
                calendar_item_list.append(new_calendar_item)
            CalendarItem.objects.bulk_create(calendar_item_list)

在外壳中工作:

test = RecurringEventItem.objects.get(pk='42f59a0ba1ac40858256a607fd8c57a3')
test_2 = test.delegated_to.all()
test_2
<QuerySet [<Contact: Test Person>]>

应用程序运行时QuerySet的结果。

<QuerySet []>

0 个答案:

没有答案