问题描述
py
class Scenes(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Tech(models.Model):
tech = models.CharField(max_length=30)
scenario = models.ManyToManyField('Scenes')
def __str__(self):
return self.tech
class UserLog(models.Model):
tech_id = models.ForeignKey(Tech, on_delete=models.CASCADE)
....#other fields
它会生成一个额外的表,称为pages_tech_scenario(pages是我的应用程序名称)
It generates one extra table called pages_tech_scenario (pages is my app name)
我在数据库(postgres)中填充的表如下所示
My populated tables in database (postgres) looks like below
pages_tech_scenario
id | tech_id | scenes_id
----+---------+-----------
1 | 1 | 1
4 | 2 | 1
5 | 2 | 2
6 | 2 | 3
7 | 2 | 4
8 | 2 | 5
9 | 3 | 3
10 | 4 | 1
11 | 4 | 2
12 | 4 | 3
pages_scenes
id | name
----+----------
1 | poweron
2 | poweroff
3 | sleep
4 | wakeup
5 | switch
pages_tech
id | tech
----+------
2 | CDMA
3 | GSM
4 | 5G
1 | LTE
pages_userlog
id | data_location | pc | username | target | data_type | description | status | submission_time | upload_now | string_submission_time | tech_id_id
----+------------------------------------------------------+---------+----------+--------+-----------+-------------+-------------+-----------------------+------------+------------------------+------------
39 | C:\My Files\testFolder | lab0128 | ananagra | SDX55 | crash | | In Progress | 2020_02_12_T_17_45_04 | f | | 2
19 | C:\My Files\testFolder | lab0034 | sujaraj | SDX55 | crash | | In Progress | 2020_02_12_T_15_46_59 | f | 111 | 1
在此,对于pages_userlog,第一个条目id = 39的tech_id_id为2,与CDMA等效.输入表单时,我选择了CDMA的一种情况(例如 sleep )(因为CDMA指向所有5种情况,可以从 pages_tech_scenario 表中看到).
Here, for pages_userlog first entry id=39 has tech_id_id is 2 which is equivalent to CDMA. While entering the form, I had selected one of the scenario (say sleep) field of CDMA (as CDMA points to all 5 scenarios, can be seen from pages_tech_scenario table).
如何仅从CDMA中检索 sleep 方案,而不是其指向的所有方案?.
How can I retrieve only sleep scenario from CDMA instead of all the scenarios its pointing to?.
如何通过指定tech_id和scenes_id从pages_tech_scenario获取ID?.
How to get the id from pages_tech_scenario by specifying tech_id and scenes_id?.
推荐答案
您可以从UserLog中命名该字段:
You can name the field from UserLog:
tech = models.ForeignKey(Tech, on_delete=models.CASCADE)
这样,您可以通过tech_id
而不是tech_id_id
This way you can reference the id by tech_id
instead of tech_id_id
UserLog.objects.get(pk=1).tech.scenario.get(name="sleep")
Tech.scenario.through.objects.get(tech_id=tech_id, scenes_id=scenes_id).id
这篇关于如何在Django manytomanyfield中访问生成的表字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!