Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get_or_create, how to say commit=False

Tags:

python

django

Suppose I have this model:

class SocialGroupMembers(models.Model):
    social_group = models.ForeignKey(SocialGroup, related_name="members")
    profile = models.ForeignKey(Profile)
    date_joined = models.DateTimeField(auto_now_add=True)
    added_by = models.ForeignKey(User)
    approved = models.BooleanField(default=False)

If I do:

obj, created = SocialGroupMembers.objects.get_or_create(
        social_group=social_group, profile=profile)
    # this will give integrity error that added_by can not be null

I don't want to include added_by field in filter criteria. I want to save added_by field later. Something like commit=False to tell Django that I have plans to add more fields later:

obj, created = SocialGroupMembers.objects.get_or_create(commit=False,
        social_group=social_group, profile=profile)
if created:
    obj.added_by = request.user
    obj.save()
else:
    #do something

I know there are alternatives e.g. I can use ObjectDoesNotExist. But Is there any way to achieve the desired functionality in get_or_create?

The reason I want to exclude the added_by field is because may be another user has already added another user Profile.

like image 387
Aamir Rind Avatar asked Nov 28 '12 17:11

Aamir Rind


1 Answers

There is a defaults argument you can pass to get_or_create to populate this data for newly created objects which are not used in the filtering:

defaults = {'added_by': request.user}
obj, created = SocialGroupMembers.objects.get_or_create(
        social_group=social_group, profile=profile, defaults=defaults)

https://docs.djangoproject.com/en/1.4/ref/models/querysets/#get-or-create

like image 157
Mark Lavin Avatar answered Oct 10 '22 20:10

Mark Lavin