File: test_o2m_m2m.py

package info (click to toggle)
python-sqlalchemy-utils 0.30.12-2~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 1,056 kB
  • sloc: python: 10,350; makefile: 160
file content (76 lines) | stat: -rw-r--r-- 2,408 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import sqlalchemy as sa

from sqlalchemy_utils import aggregated
from tests import TestCase


class TestAggregateOneToManyAndManyToMany(TestCase):
    dns = 'postgres://postgres@localhost/sqlalchemy_utils_test'

    def create_models(self):
        product_categories = sa.Table(
            'category_product',
            self.Base.metadata,
            sa.Column('category_id', sa.Integer, sa.ForeignKey('category.id')),
            sa.Column('product_id', sa.Integer, sa.ForeignKey('product.id'))
        )

        class Catalog(self.Base):
            __tablename__ = 'catalog'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))

            @aggregated(
                'products.categories',
                sa.Column(sa.Integer, default=0)
            )
            def category_count(self):
                return sa.func.count(sa.distinct(Category.id))

        class Category(self.Base):
            __tablename__ = 'category'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))

        class Product(self.Base):
            __tablename__ = 'product'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))
            price = sa.Column(sa.Numeric)

            catalog_id = sa.Column(
                sa.Integer, sa.ForeignKey('catalog.id')
            )

            catalog = sa.orm.relationship(
                Catalog,
                backref='products'
            )

            categories = sa.orm.relationship(
                Category,
                backref='products',
                secondary=product_categories
            )

        self.Catalog = Catalog
        self.Category = Category
        self.Product = Product

    def test_insert(self):
        category = self.Category()
        products = [
            self.Product(categories=[category]),
            self.Product(categories=[category])
        ]
        catalog = self.Catalog(products=products)
        self.session.add(catalog)
        products2 = [
            self.Product(categories=[category]),
            self.Product(categories=[category])
        ]
        catalog2 = self.Catalog(products=products2)
        self.session.add(catalog)
        self.session.commit()
        assert catalog.category_count == 1
        assert catalog2.category_count == 1