使用来自另一个django模型的自定义数据填充Django ManyToManyField

时间:2014-09-10 06:41:28

标签: django

我有app1的 Model1

class Event(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(max_length=500)
    eventdate = models.DateField()
    created = models.DateTimeField(auto_now_add=True)
app2的

模型1

class Register(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    select_the_event = models.ManyToManyField(Event)
    created = models.DateTimeField(auto_now_add=True)

事件数据库包含一整年的事件信息。

如何填充" select_the_event"哪些活动列表在接下来的60天内有效?

2 个答案:

答案 0 :(得分:2)

如果您有Register模型的forms.py,那么在RegisterForm类中您可以添加属性

class RegisterForm(forms.ModelForm):
    ....
    ....
    select_the_event = forms.ModelMultipleChoiceField(queryset=Event.objects.filter(
        event_date__range=[datetime.datetime.now().date(), datetime.datetime.now().date() + datetime.timedelta(60)])
)

答案 1 :(得分:0)

在您的ModelForm中,为select_the_event的ModelMultipleChoiceField分配自定义查询集:

select_the_event = forms.ModelMultipleChoiceField(
                     queryset=Event.objects.filter(...))