[英]Django filter data in table based on value from another table?
views.py:意见.py:
def dcuinterval(request):
var7 = dcu.objects.all()
MU_count = Meter_Mapping_Table.objects.filter(DCU_id=dcu.id).count()
d = {
'MU_count': MU_count, 'var7': var7,
}
return render(request, 'dcu_interval.html', d)
Models.py:模型.py:
class dcu(models.Model):
id = models.AutoField(unique=True, editable=False, primary_key=True)
Asset = models.CharField(max_length=128)
IMEI_Number = models.CharField(max_length=128)
def __str__(self):
return self.Asset
class Meter_Mapping_Table(models.Model):
mid = models.AutoField(unique=True, editable=False, primary_key=True)
Meter_id = models.CharField(
max_length=128, help_text='(ID of the Meter table)')
MU_id = models.CharField(max_length=150)
DCU_id = models.CharField(max_length=150, null=True, blank=False)
def __str__(self):
return self.Meter_id
how to filter the data based on the another table filed?如何根据提交的另一个表过滤数据?
i need to filter the DCU_id based on the DCU tables id field DCU_id =1;我需要根据 DCU 表 id 字段 DCU_id =1 过滤 DCU_id; DCU.id=1; DCU.id=1; ANSWER: MU_count=1 like this i need to filter and show that count答案:MU_count=1 像这样我需要过滤并显示该计数
You can use:您可以使用:
Meter_Mapping_Table.objects.filter(DCU_id='1').count()
Although that is the answer, you need to really consider your database design and make use of ForeignKey
relationships.虽然这是答案,但您需要真正考虑您的数据库设计并利用ForeignKey
关系。 Having a foreign key as a CharField
is not recommended.不推荐使用外键作为CharField
。
I would suggest the following:我建议如下:
Change:改变:
DCU_id = models.CharField(max_length=150, null=True, blank=False)
To:到:
DCU = models.ForeignKey(dcu, null=True, blank=False)
Then you can query like so:然后你可以这样查询:
Meter_Mapping_Table.objects.filter(DCU=1).count()
Note: Also consider following Django's Naming Convention for Models .注意:还要考虑遵循Django 的模型命名约定。 As this will aid readability for other developers.因为这将有助于其他开发人员的可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.