Home > Blockchain >  How to query a specific field in a model that has the same name as another field of another model
How to query a specific field in a model that has the same name as another field of another model

Time:05-13

I'm trying to render the device that has the same name as the Gateway in the query so I created three models (The plant model has nothing to do with this issue so skip it ) as you can see in the models.py :

from django.db import models
infos_type= (
    ('ONGRID','ONGRID'),
    ('PV','PV'),
    ('HYBRID','HYBRID'),
)
infos_status= (
    ('etude','Etude'),
    ('online','Online'),
    ('Other','Other'),
)
infos_Device= (
    ('Rs485','Rs485'),
    ('lora','lora'),
    ('Other','Other'),
)

class new_Plant(models.Model):
    name=models.CharField(max_length=20)
    adress=models.CharField(max_length=50)
    type=models.CharField(max_length=20,choices=infos_type)
    location=models.CharField(max_length=50)
    list_gateway=models.CharField(max_length=50)
    status=models.CharField(max_length=50,choices=infos_status)
    
    def __str__(self):
        return self.name    
    #class Meta:
        #db_table="website"
        
class new_Gateway(models.Model):
    gatewayname=models.CharField(max_length=20)
    slavename=models.CharField(max_length=20)
    list_devices=models.CharField(max_length=20)
    def __str__(self):
        return self.gatewayname
    
    
class new_Device(models.Model):
    Gateway_Name=models.CharField(max_length=20)
    DeviceName=models.CharField(max_length=20)
    slavename=models.CharField(max_length=20)
    adress=models.CharField(max_length=20)
    baud_rate=models.CharField(max_length=20)
    connection_type=models.CharField(max_length=20,choices=infos_Device)
    def __str__(self):
        return self.DeviceName
    

       
    
# Create your models here.

Now as I said I want to render in a specific page , the device that Has "Gateway_Name" field same as the Gateway "gatewayname" field.

in my views.py this is what I tried but it doesn't work :

def gatewaysdevice(request,id):
    gateway=new_Gateway.objects.get(id=id)
    result=new_Device.objects.filter(Gateway_Name__contains=new_Gateway(gatewayname))
    return render(request, 'website/gatewaysdevice.html',{'result':result})

CodePudding user response:

You can try this query in your code:

result=new_Device.objects.filter(Gateway_Name__contains=gateway.gatewayname)

#If you encounter any type(object) error then use str(gateway.gatewayname).

Note : You can go with '__icontains' in above query which ignores lower and uppercase entries in Gateway_Name field for better approach.

  • Related