PEREYO
PEREYO

Reputation: 137

How to create an unique object for a Django model with a many to many field?

I want to create an unique object ( It couldn't exist another instance with the same fields). This object has a many to many relationship which is responsible of making it unique.

The object is a thread of messages, and this thread is a conversation between two users (really it could be between more users because I'm using a many to many field, but I'm only interested between two users ) .

class Thread(models.Model):
    users = models.ManyToManyField(User, null=True,blank=True, related_name='threads')

class Mensaje(models.Model):
    thread = models.ForeignKey(Thread, related_name='mensajes')#messages

When an user send a message to another user, if the thread doesn't exist it will be created, and if it exists the messages will be related with this thread.

I'm trying something like that:

thread = Thread.objects.get_or_create( users= [user1, user2])

But I have the next exception:

Exception Value: int() argument must be a string or a number, not 'list'

Any suggestions?

Thanks.

Upvotes: 1

Views: 1352

Answers (1)

karthikr
karthikr

Reputation: 99620

You can not use get_or_create directly for m2m. You can do something like this:

user_list = [user1, user2]
thread_qs = Thread.objects.filter(users=user_list[0])
for user in user_list[1:]:
    thread_qs= thread_qs.filter(users=user)
try:
    thread = thread_qs.get() #get if only one object. 
except MultipleObjectsReturned as e:
    print 'Multiple Objects Returned'
except ObjectDoesNotExist: #create object if does not exist
    thread = Thread.objects.create()
    thread.users.add(user_list)
    thread.save() #this might be redundant

Upvotes: 1

Related Questions