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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With