Python Django 1.9中的内部联接
我有这两种型号:Python Django 1.9中的内部联接,python,sql,django,postgresql,django-queryset,Python,Sql,Django,Postgresql,Django Queryset,我有这两种型号: 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 = (('i
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
。在我看来,我使用以下代码从模型中获取数据:
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详细信息(请求,id):
)
我需要从ModelInteractions
中选择comm
,其中id2
=id
(请求时收到id)
当前代码返回:
Cannot resolve keyword 'ModelInteractions' into field. Choices are: id, name
让您的模型像这样,然后进行迁移和迁移
然后运行相同的查询直到这里
condition = Q(name__icontains=names[0])
for name in names[1:]:
condition &= Q(name__icontains=name)
那就换这一行
condition &= Q(interaction__id2=id)
然后
在django,你不能这样做,你需要与foreignkey建立关系,然后你可以使用它,或者如果你不想提及关系,可以使用原始查询扫描你,请为我的案例演示一个例子?谢谢!我应该提供一个默认值吗?迁移时,我得到了这个django.db.utils.IntegrityError:列“interaction_id”包含空值
。对于表中的旧数据,您可以使用空值,如果不需要旧数据,您可以删除数据库并创建一个新的数据库并进行迁移,或者使用default=1
condition &= Q(interaction__id2=id)
models = Models.objects.filter(condition)