mysql每个id / name返回1行

时间:2018-05-23 18:10:41

标签: python sql flask jinja2 peewee

我想加入3个表并获得它们的结果而没有任何重复

SELECT * FROM `database`.project 
INNER JOIN post on project.id = post.project_id 
INNER JOIN media on media.post_id = post.id 
;

当前输出

enter image description here

我想知道输出是否类似于

floaty
Headphone
fasion + technolgie

我尝试使用distinct功能。但是它只返回我希望返回连接表的名称,因为我仍然想要使用该数据。

  

models.py

我正在使用Project.with_media()全部

"""models."""
from app import db
from peewee import *
import datetime


class Project(Model):
    """Projects."""

    name = CharField(unique=True)
    content = CharField()
    created_date = DateTimeField(default=datetime.datetime.today())

    class Meta(object):
        """Select database."""

        database = db

    def get_project_media(self):
        """Grab image from get_posts."""
        post = Post.select().where(Post.project_id == self).get()
        return Media.select().where(Media.post_id == post).get().media

    def check_media(self):
        """Check if project has media."""
        try:
            post = Post.select().where(Post.project_id == self).get()
            Media.select().where(Media.post_id == post.id).get()
            print('True')
            return True
        except DoesNotExist:
            print('False')
            return False
  

这是我的呼唤所以我可以在jinja引擎上显示它

    def with_media():
        """Grab image from get_posts."""
        return (Project.select(Project, Post, Media)
                    .join(Post)
                    .join(Media)
                    .where(Post.id == Media.post_id
                           and
                           Project.id == Post.project_id))

    def posts(self):
        """Return all posts that are accosicated with this project."""
        return Post.select().where(Post.project_id == self)

    def media_post(self):
        """Return all posts that are accosicated with this project."""
        post = Post.select().where(Post.project_id == self)
        return post.get_media()
        # return Media.select().where(Media.post_id == post).get()



class Post(Model):
    """Model for posts."""

    project = ForeignKeyField(Project, backref='Post', null=True, default=None)
    name = CharField()
    content = TextField()
    "Media Model"
    "Category Model"
    "Project Model"
    created_date = DateTimeField(default=datetime.datetime.today())

    class Meta(object):
        """Select database."""

        database = db

    def get_category(self):
        """Grab all the posts from project."""
        return (Category.select()
                .where(Category.post_id == self))

    def get_media(self):
        """Grab all media from this post."""
        return (Media.select()
                .where(Media.post_id == self))

    def standalone():
        """Return a model of all posts not bound to a project."""
        return (Post.select()
                .where(Post.project.is_null())
                .order_by(Post.created_date.desc()))

    def date():
        """Return dates order_by."""
        return(Post.select()
               .order_by(Post.created_date.desc()))


class Media(Model):
    """Media for post."""

    post = ForeignKeyField(Post, backref='Media')
    media = CharField()

    class Meta(object):
        """Select database."""

        database = db


class Category(Model):
    """model for all avaible category's."""

    post = ForeignKeyField(Post, backref='Category')
    name = CharField()

    class Meta(object):
        """Select database."""

        database = db

    def get_name():
        """Get all category's without overlaping."""
        categorys = Category.select()
        categoryList = []
        for category in categorys:
            categoryName = category.name.title()
            if categoryName not in categoryList:
                categoryList.append(categoryName)
        return categoryList


def initialize():
    """Create tables."""
    db.connect()
    db.create_tables([Category, Project, Post, Media], safe=True)
    db.close()
  

main.py

我想用media()函数调用项目,这样我就可以使用数据库项来调用图像和显示内容

<ul class='projects'>
    {% for project in projects.with_media() %}
            {% if loop.index <= 3 %}
                <li class='project_w'>
                    <img src="{{project.media_post()}}" alt="">
                    <a href="{{url_for('project', id=project.id)}}">
                    <h2>{{project.name}}</h2>
                    </a>
                </li>
            {% else %}
                <li class='project_h'>
                    <img src="{{project.post.media.media}}" alt="">
                    <a href="{{url_for('project', id=project.id)}}">
                    <h2>{{project.name}}</h2>
                    </a>
                </li>
            {% endif %}
    {% endfor %}
</ul>

1 个答案:

答案 0 :(得分:0)

问题:

.where(Post.id == Media.post_id
                       and
                       Project.id == Post.project_id))

而不是“和”,你必须使用“&amp;”。请参阅http://docs.peewee-orm.com/en/latest/peewee/query_operators.html