1

我有几个模型,对如何创建所有关联有点困惑。我有个人资料、事件、消息和收件箱。每个配置文件都有一个包含事件的 eventList。每条消息也与一个事件相关联。每个收件箱都与一个配置文件和多条消息相关联。我想要做的是,每当创建消息对象时,将其插入到每个用户的收件箱中,这些用户在其 eventList 中持有与该消息关联的事件。提供我的模型和我正在编写的视图:

class Profile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=50)
    eventList = models.ManyToManyField(Event, blank="TRUE", null="TRUE", related_name='event_set+')
    ownedEvent = models.ManyToManyField(Event, blank="TRUE", null="TRUE", related_name='owned_set')
    def __unicode__(self):
            return self.name

class inbox(models.Model):
    def __unicode__(self):
        return self.user.name
    user = models.OneToOneField(Profile)
    message = models.ManyToManyField(message, blank="TRUE", null="TRUE")
    read = models.BooleanField(default = 0)

class message(models.Model):
    def __unicode__(self):
        return unicode(self.body)
    def save(self, *args, **kwargs):
        if not self.id:
            self.created = datetime.datetime.today()
        super(message, self).save(*args, **kwargs)
    body = models.CharField(max_length=250)
    eid = models.ForeignKey(Event)


@login_required
def sendMail(request):

    event_id = request.POST['event_id']
    e = Event.objects.get(id = event_id)
    text = request.POST['body']

    m = message(eid = e, body = text)
    m.save()

    users = e.eventList_set.all()

    return HttpResponse(status = 200)
4

1 回答 1

0

如果您希望这种情况始终发生,您可以将相关代码放入message.save()方法或保存后信号处理程序中。如果只是为了这个视图,那么你可以把代码放在那里。无论哪种情况,这都应该有效:

# msg is the message instance
for box in inbox.objects.filter(user__eventList=msg.eid):
    box.message.add(msg)
于 2013-08-07T18:25:37.617 回答