Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get_or_create and ManytoManyField

Tags:

python

django

I'm previously used ForeignKey.

Model

class Phone_request_list(models.Model):
    who = models.IntegerField(null=True)
    whose = models.ForeignKey(User)

View

def phone_request(request):
    user_id = request.user.id
    uuid = request.GET.get('uuid')
    profile_id = profiles.objects.get(uuid=uuid).user_id
    p,created = Phone_request_list.objects.get_or_create(who=user_id,whose_id=profile_id)
    p.save()

but now I want to change my model to manytomany field

class Phone_request_list(models.Model):
    who = models.IntegerField(null=True)
    whose = models.ManyToManyField(User) 

This time how can I check whose with who in get_or_create. Please help me.

like image 203
SAFEER N Avatar asked Mar 11 '14 15:03

SAFEER N


1 Answers

def phone_request(request):
    user_id = request.user.id
    uuid = request.GET.get('uuid')
    profile_id = profiles.objects.get(uuid=uuid).user_id
    p,created = Photo_request_list.objects.get_or_create(who=user_id)
    p.whose.add(profiles.objects.get(uuid=uuid))
    p.save()

btw, you didn't need that final p.save() when you were using a ForeignKey but you do now you have a M2M

like image 198
Adam Spence Avatar answered Sep 20 '22 16:09

Adam Spence