2
我有以下模型,通過外鍵和ManyToMany關係鏈接。Django - 如何過濾ManyToMany模型對象?
from django.db import models
from django.contrib.auth.models import User
class AssetMetadata(models.Model):
id = models.DecimalField(6).auto_creation_counter
material_id = models.CharField(max_length=256, blank=True)
series_title = models.CharField(max_length=256, blank=True)
season_title = models.CharField(max_length=256, blank=True)
season_number = models.IntegerField(default=0)
episode_title = models.CharField(max_length=256, blank=True)
episode_number = models.IntegerField(default=0)
synopsis = models.TextField(max_length=1024, blank=True)
ratings = models.CharField(max_length=256, blank=True)
def __str__(self):
return self.material_id
class Batch(models.Model):
material_id = models.ManyToManyField(AssetMetadata)
user = models.ForeignKey(User, unique=True)
def __str__(self):
return 'Batch_' + str(self.pk) + '_' + self.user.username
我可以看到,這工作,模型已經創建和關係工作,如你所期望的。從控制檯輸出中可以看到:
>>> from asset_db.models import Batch
>>> Batch.objects.values()
<QuerySet [{'user_id': 1, 'id': 1}, {'user_id': 3, 'id': 2}]>
當我遷移模型時,它創建了下列表格(添加了以便您可以看到關係)。
asset_db_batch:
id | user_id
____________
1 | 1
2 | 3
asset_db_batch_material_id:
id | batch_id | assetmetadata_id
______|_____________|________________
1 | 1 | 1
2 | 1 | 2
3 | 1 | 6
4 | 1 | 8
5 | 1 | 4
6 | 2 | 8
7 | 2 | 2
8 | 2 | 4
9 | 2 | 7
我的問題是我怎麼篩選Batch
對象返回關聯到batch_id
的項目?基本上,我如何在Django重新創建SQL查詢:
SELECT * FROM asset_db_batch_material_id
INNER JOIN asset_db_batch
ON asset_db_batch_material_id.batch_id = asset_db_batch.id
INNER JOIN asset_db_assetmetadata
ON asset_db_batch_material_id.assetmetadata_id = asset_db_assetmetadata.id
WHERE user_id = 1
由於這樣做完美。它理解我遇到的過濾器語法,你能推薦任何有用的資源來解釋這是更詳細的嗎? – Lewis909
想不起任何事情。我的規則是「當有疑問總是嘗試'__'」 – e4c5
我相信你已經看到了這個,https://docs.djangoproject.com/en/1.11/topics/db/queries/#lookups-that-span-relationships是的,這是可以忘記的。 – e4c5