Home > OS >  Django How to check id of ForeignKey?
Django How to check id of ForeignKey?

Time:04-08

I have models.py like this. which api_key in table UserKey is ForeignKey to api_key in table DeviceKey.

class DeviceKey(models.Model):
    
    api_key=models.CharField(max_length=100,unique=True)
    created=models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.api_key
   

class UserKey(models.Model):
    api_key=models.ForeignKey(DeviceKey,on_delete=models.CASCADE)

    def __str__(self):
        return self.username

The data in table DeviceKey and Userkey show like this code.

Table DeviceKey
id  api_key
1    abc1
2    abc2

Table Userkey
id  api_key_id
1     1

I want to check if api_key exists in table Userkey but I can't search with text beacause table UserKey keep api_key as id. So, I have to get id from table DeviceKey like this code

key="abc2"
if UserKey.objects.filter(username=username,api_key_id=DeviceKey.objects.get(api_key=key).values_list('id')).exists():

It show error like this.

'DeviceKey' object has no attribute 'values_list'

How to fix it?

CodePudding user response:

This should work for you if your api_key in Device_key is 'abc1'

   UserKey.objects.filter(api_key__api_key='abc1').exists()

CodePudding user response:

While using foreign key, try to make use of related_name property in the table that is having (many relationship).

class DeviceKey(models.Model):

    api_key=models.CharField(max_length=100,unique=True)
    created=models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.api_key


class UserKey(models.Model):
    api_key=models.ForeignKey(DeviceKey,on_delete=models.CASCADE, related_name='user_key')

    def __str__(self):
        return self.username

If you want to get the records of 'api_key' of model 'DeviceKey' in realtionship with 'UserKey' model rows. You can make use of 'realted_name' as below

api_key_obj = DeviceKey.objects.get(api_key='api_key_value')

This gives list of all the rows of 'UserKey' that are in relationship with the 'api_key_obj'. api_key_obj.user_key

Returns true or false depending on the existence of relationship between 'DeviceKey' and 'UserKey' for 'api_key_obj'.

api_key_obj.user_key.exists()
  • Related