简体   繁体   中英

peewee constrain integer based on a field in another model

I am working on a mock-webshop homework and have some models for users, products, tags and Transactions.

class Product(peewee.Model):
    description = peewee.CharField()
    price_in_cents = peewee.IntegerField()
    stock = peewee.IntegerField()
    tags = peewee.ManyToManyField(Tag)

    class Meta:
        database = db

class Transaction(peewee.Model):
    seller = peewee.ForeignKeyField(User)
    buyer = peewee.ForeignKeyField(User)
    product = peewee.ForeignKeyField(Product)
    amount =peewee.IntegerField()

I've read through de documentation but was unable to find how to set a constraint in amount within Transaction so that it can be no larger than the stock value corresponding to the product class, and if possible how to tell it that seller and buyer cannot be the same.

Databases have varying levels and types of support for providing a CHECK type constraint that involves traversing a join. I think what you want is likely some form of CHECK constraint, but how exactly you accomplish that will depend on your db. Alternatively you can use a pre-INSERT trigger that does the lookup and raises an error if the value is invalid, but you'd probably also need a corresponding post-UPDATE hook on the product table to also raise an error if it violates the constraint for related transactions.

Peewee CHECK constraint documentation:

Example of basic single-table check:

class Transaction(Model):
    amount = DecimalField(decimal_places=2, constraints=[Check('amount > 0')])

For your second part, you can do something like:

seller = peewee.ForeignKeyField(User, constraints=[Check('seller_id != buyer_id')])
buyer = peewee.ForeignKeyField(User)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM