-1

Want to compare(if they are same or not) 'map_id' of 'map' model with 'uni_id' of 'Uni' model, return if they are same. Note: models map and Uni are also in different databases.

Below are the two models:

 class map(models.Model):
       job_id = models.AutoField(db_column='job_id', primary_key=True)
       company = models.CharField(max_length=255, blank=True, null=True)
       map_id = models.CharField(db_column='Map_ID', max_length=255, blank=True, null=True)
      
       class Meta:
             managed = True
             db_table = 'Map'


  class Uni(models.Model):
        uni_id = models.BigAutoField(db_column='Uni_ID', primary_key=True)  
        comp_name = models.TextField(blank=True, null=True)
        name = models.TextField(blank=True, null=True)

        class Meta:
              managed = True
              db_table = 'Uni'

I want to filter map_id from map model whose value is equal to uni_id from Uni. below is the code which i tried:

   obj_map = map.objects.using("Map").filter(map_id=pk).filter(map_id__in=F('uni_id'))
SSS
  • 73
  • 11

1 Answers1

1

You could say something like this:

obj_map = map.objects.filter(map_id=pk) if Uni.objects.filter(uni_id=pk).exists() else None

This will check if Uni object with that id value exists, and if it does, then it will try to find the map object with that id. If Uni object doesn't exist, or it does but the map object with that id doesn't exist, you'll just end up with None value in your obj_map field. Use if obj_map: to perform further calculations.

NOTE: Please use uppercase convention for Class names in Python. Change class map(models.Model) to class Map(models.Model). By the way, I don't know what is the use case of this code, but comparing unique id's of two different models is not safe at all (for example if id fields are auto generated). I'm not either sure why are you using db_table so I left it out of the example.

  • Hi @Aleksandar Mijatović thanks for your answer, anyway i solved my issue. About name of python class, its capital in my code, i just posted demo code here that's why class name in lowercase. – SSS Sep 15 '20 at 14:24