I want to create simple chat system, my models:
class Conversation(models.Model):
users = models.ManyToManyField(User, related_name='users')
date = models.DateTimeField(auto_now_add=True)
class Message(models.Model):
user = models.ForeignKey(User)
conversation = models.ForeignKey(Conversation, related_name='conversation')
content = models.TextField()
date = models.DateTimeField(auto_now_add=True)
and my view:
def conversation(request, username):
recipient = User.objects.get(username=username)
conversation, created = Conversation.objects.get_or_create(
users__in=[recipient, request.user]
)
if created:
conversation.users.add([recipient, request.user])
I want create users connection by create conversation with manytomany field.
When i go to /conversations/user_name get_or_create check if conversation exists and if not then create new conversation with current logged user and user from url.
My problem is:
MultipleObjectsReturned at /conversations/user_name
get() returned more than one Conversation -- it returned 2!
How can i solve it? Probably its problem with this manytomany field.. How i can limit users__id lookup to 1?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…