Reputation: 151
Here is the my code in model
class Role(models.Model):
name_role = models.CharField(max_length=255)
def __unicode__(self):
return self.name_role
class UserProfile(models.Model):
user = models.OneToOneField(User)
role = models.ForeignKey(Role)
create_by = models.IntegerField(null=True)
create_date = models.DateTimeField(null=True)
modified_by = models.IntegerField(null=True)
modified_date= models.DateTimeField(null=True)
status = models.IntegerField(default=1)
When A role will be deleted, I want to check if any UserProfile object is related to the role object. How can I do this?
Upvotes: 0
Views: 892
Reputation: 20339
I think you are expecting this
role = Role.objects.get(name_role="rolename")
role.user_profile_set.all() #check if any before delete
Try this also
role.userprofile_set.all()
Upvotes: 0
Reputation: 4245
You can do that by accessing the reverse ForeignKey
field from Role. Something like:
if role_instance.userprofile_set.all():
print "Care, role is related to userprofile instances"
else:
print "You are safe to go"
Upvotes: 1