我想将单个squawks插入Room对象,以便我可以插入到数据库中。我该怎么做?
我试过,Room(squawk = squawk object),但这似乎不起作用。
class Squawk(models.Model):
username = models.ForeignKey(User)
message = models.CharField(max_length=160)
time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return str(self.username) + ' - ' + self.message
class Room(models.Model):
title = models.CharField(max_length=160)
created = models.DateTimeField(auto_now_add=True)
users = models.ManyToManyField(User)
squawks = models.ManyToManyField(Squawk)
def __unicode__(self):
return self.title
答案 0 :(得分:2)
from django.shortcuts import get_object_or_404
# get Room instance by id or raise 404 page if not found
room = get_object_or_404(Room,pk = id)
# add squawk to many-to-many relation
room.squawks.add(squawk_object)