简体   繁体   中英

how to compare two fields of different models in Django query-set?

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'))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM