python - 加入 Django View

标签 python mysql django join django-views

我的 Django 应用程序中有 2 个模型。 两种型号对应的表格为:

Table 1:
+-------------+---------+------+-----+---------+----------------+
| Field       | Type    | Null | Key | Default | Extra          |
+-------------+---------+------+-----+---------+----------------+
| id          | int(11) | NO   | PRI | NULL    | auto_increment |
| post_id     | int(11) | NO   | MUL | NULL    |                |
| user_id     | int(11) | NO   | MUL | NULL    |                |
+-------------+---------+------+-----+---------+----------------+

Table2:
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| p_text        | varchar(200) | NO   |     | NULL    |                |
| p_slug        | varchar(50)  | YES  | MUL | NULL    |                |
| user_id       | int(11)      | NO   | MUL | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+

现在我想要的是以最佳方式在我的 Django View 中编写与以下查询等效的内容?我想写的查询是一个简单的连接:

select B.p_slug from Table1 A, Table2 B where A.post_id = B.id;

我试过了,但无法正常工作。有什么帮助吗?如何在Django View 中实现上述查询

模型是:模型1:

class Model1(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    post = models.ForeignKey(Model1)
class Model2(models.Model):
    p_text = models.CharField(max_length=200)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    p_slug = models.SlugField(null=True,blank=True)

最佳答案

试试这个:Model2.objects.filter(pk__in=Model1.objcts.values_list('post_id', flat=True)).values('p_slug')。希望对您有所帮助。

关于python - 加入 Django View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30385206/

相关文章:

python - 使用pypy2.2时导入Numpypy

python - 在处理调查数据时,如何合并 pandas 中的列?

mysql - 插入从锁定行中获取的值的问题

php - 口音在工作台中显示不正确,但在 php 网站中显示正常

Python 多处理似乎几乎不可能在类内完成/使用任何类实例。它的预期用途是什么?

python - Scipy.optimize.curvefit 对数函数

mysql - sphinx 搜索 : 1064 can not use HAVING with attribute not related to GROUP BY

python - 运行时错误: main thread is not in main loop using Matplotlib with Django

python - django manage.py createsuperuser 不接受用户名

python - 如何在 Django Rest + 使用 Django Rest Throttling 中防止暴力攻击