Help with getting a record id

help needed, Here is a model with having the User model as a foreign key

class UserMembership(models.Model):
    user = models.OneToOneField(User, related_name='user_membership', on_delete=models.CASCADE)
    membership = models.ForeignKey(Membership, related_name='user_membership', on_delete=models.SET_NULL, null=True)
    reference_code = models.CharField(max_length=100, default='', blank=True)

on my views i am checking if the user exists in the above table

def verify(request):
    user = request.user
    check_membership_status = UserMembership.objects.filter(user = user).exists()

    if check_membership_status == True:
         # do something
         pass

inside the do something condition i want to print out the record of the user from the “UserMembership” model and extract the the record id. how can i do that

Hi kalistos1, .exists() returns the boolean. However you can fetch the UserMembership instance via .first(). If the record doesn’t exist, it’ll return None.

def verify(request):
    user = request.user
    membership_status = UserMembership.objects.filter(user = user).first()

    if membership_status:  # an instance is a Truth-y value
         # do something
         pass

You can also try to fetch the instance from the User instance via the related_name.

def verify(request):
    user = request.user
    try:
        membership_status = user.user_membership
        # do something
    except UserMembership.DoesNotExist:
        # other

resolved, thanks @CodenameTim