2017-08-01 90 views
2

我有這兩種模式:內連接在Django 1.9

class ModelInteractions(models.Model): 
    id1 = models.IntegerField(primary_key=True) 
    id2 = models.IntegerField() 
    comm = models.TextField(blank=True, null=True) 

    class Meta: 
     managed = False 
     unique_together = (('id1', 'id2'),) 


class Models(models.Model): 
    id = models.IntegerField(primary_key=True) 
    name = models.TextField() 

    class Meta: 
     managed = False 

,我想也comm選擇。在我看來,我用下面的代碼來Models獲取數據:

condition = Q(name__icontains=names[0]) 
for name in names[1:]: 
    condition &= Q(name__icontains=name) 
# ↓↓↓ this line is for what I need but it doesn't work 
condition &= Q(ModelInteractions__id2=id) 

models = Models.objects.filter(condition) 

id是在請求(def details(request, id):)接收。

我需要從ModelInteractions中選擇comm,其中id2 = id(根據請求收到ID)。

當前的代碼返回:

Cannot resolve keyword 'ModelInteractions' into field. Choices are: id, name 
+1

你不能像這樣做在Django,你需要有外鍵關係,那麼你可以使用它,否則,如果你不使用原始查詢要提的關係 – Exprator

+0

你能,請,爲我的案例展示一個例子? – feci

回答

1
class ModelInteractions(models.Model): 
    id1 = models.IntegerField(primary_key=True) 
    id2 = models.IntegerField() 
    comm = models.TextField(blank=True, null=True) 

    class Meta: 
     managed = False 
     unique_together = (('id1', 'id2'),) 


class Models(models.Model): 
    id = models.IntegerField(primary_key=True) 
    name = models.TextField() 
    interaction= models.ForeignKey(ModelInteractions,on_delete=models.CASCADE) 

讓你的模型是這樣,那麼makemigrations和遷移

然後運行相同的查詢到這裏

condition = Q(name__icontains=names[0]) 
for name in names[1:]: 
    condition &= Q(name__icontains=name) 

然後改變這一行

condition &= Q(interaction__id2=id) 

然後

models = Models.objects.filter(condition) 
+0

謝謝!我應該提供一個默認值嗎?我得到這個'django.db.utils.IntegrityError:列「interaction_id」在遷移時包含空值。 – feci

+0

對於表中的舊數據,您可以刪除數據庫並創建一個新數據並遷移,如果您不需要舊數據,或者給出default = 1 – Exprator