Python peewee.ForeignKeyField() Examples
The following are 18
code examples of peewee.ForeignKeyField().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
peewee
, or try the search function
.
Example #1
Source File: test_peewee.py From nplusone with MIT License | 6 votes |
def models(Base): class Hobby(Base): pass class User(Base): hobbies = pw.ManyToManyField(Hobby, backref='users') class Address(Base): user = pw.ForeignKeyField(User, backref='addresses') return Bunch( Hobby=Hobby, User=User, Address=Address, )
Example #2
Source File: data_record.py From slim with zlib License | 6 votes |
def _to_dict(self): data = {} fields = self.val._meta.fields for name, v in model_to_dict(self.val, recurse=False).items(): if isinstance(fields[name], peewee.ForeignKeyField): name = name + '_id' elif isinstance(fields[name], peewee.BlobField): v = get_bytes_from_blob(v) if self.selected != ALL_COLUMNS and (self.selected and (name not in self.selected)): continue data[name] = v if self.available_columns != ALL_COLUMNS: return dict_filter(data, self.available_columns) return data
Example #3
Source File: validate.py From slim with zlib License | 6 votes |
def get_pv_model_info(model: Union[peewee.Model, Type[peewee.Model]]): new_model_cls: Type[Model] = type(model.__class__.__name__ + 'Validator', (Model,), {}) foreign_keys = {} peewee_fields = {} ret = { 'table_name': get_pv_table_name(model), 'primary_key': get_pv_pk_name(model), 'foreign_keys': foreign_keys, 'data_model': new_model_cls, '_peewee_fields': peewee_fields } for name, field in model._meta.fields.items(): if isinstance(field, peewee.ForeignKeyField): rm = field.rel_model name = '%s_id' % name # TODO: 这里可能会出问题 foreign_keys[name] = [SQLForeignKey(get_pv_table_name(rm), get_pv_pk_name(rm))] peewee_fields[name] = field new_model_cls._append_field(name, field_class_to_schematics_field(field)) return ret
Example #4
Source File: fields.py From aiopeewee with MIT License | 6 votes |
def get_through_model(self): if not self._through_model: lhs, rhs = self.get_models() tables = [model._meta.db_table for model in (lhs, rhs)] class Meta: database = self.model_class._meta.database db_table = '%s_%s_through' % tuple(tables) indexes = ( ((lhs._meta.name, rhs._meta.name), True),) validate_backrefs = False attrs = {lhs._meta.name: ForeignKeyField(rel_model=lhs), rhs._meta.name: ForeignKeyField(rel_model=rhs), 'Meta': Meta} self._through_model = type( '%s%sThrough' % (lhs.__name__, rhs.__name__), (AioModel,), attrs) return self._through_model
Example #5
Source File: test_models.py From aiopeewee with MIT License | 6 votes |
def test_callable_related_name(): class Foo(TestModel): pass def rel_name(field): return '{}_{}_ref'.format(field.model_class._meta.name, field.name) class Bar(TestModel): fk1 = ForeignKeyField(Foo, related_name=rel_name) fk2 = ForeignKeyField(Foo, related_name=rel_name) class Baz(Bar): pass assert Foo.bar_fk1_ref.rel_model is Bar assert Foo.bar_fk2_ref.rel_model is Bar assert Foo.baz_fk1_ref.rel_model is Baz assert Foo.baz_fk2_ref.rel_model is Baz assert not hasattr(Foo, 'bar_set') assert not hasattr(Foo, 'baz_set')
Example #6
Source File: test_models.py From aiopeewee with MIT License | 6 votes |
def test_object_id_descriptor_naming(): class Person(Model): pass class Foo(Model): me = ForeignKeyField(Person, db_column='me', related_name='foo1') another = ForeignKeyField(Person, db_column='_whatever_', related_name='foo2') another2 = ForeignKeyField(Person, db_column='person_id', related_name='foo3') plain = ForeignKeyField(Person, related_name='foo4') assert Foo.me is Foo.me_id assert Foo.another is Foo._whatever_ assert Foo.another2 is Foo.person_id assert Foo.plain is Foo.plain_id with pytest.raises(AttributeError): Foo.another_id with pytest.raises(AttributeError): Foo.another2_id
Example #7
Source File: conftest.py From sanic_crud with MIT License | 5 votes |
def app(request): from peewee import SqliteDatabase, Model, CharField, IntegerField, ForeignKeyField from sanic import Sanic from sanic.log import log from sanic_crud import generate_crud db = SqliteDatabase('tests/test.db') class BaseModel(Model): class Meta: database = db class Job(BaseModel): name = CharField() description = CharField() base_pay = IntegerField() class Person(BaseModel): name = CharField() job = ForeignKeyField(Job, related_name='person_job', null=True) email = CharField() db.create_tables([Person, Job]) job = Job(name='Space garbage man', description='Collects garbage in space', base_pay=15) person = Person(name='Sanic the Hedgehog', email='gottagofeast@fast.com', job=1) job.save() person.save() test_app = Sanic(__name__) test_app.log = log generate_crud(test_app, [Person, Job]) def final(): db.drop_tables([Person, Job]) request.addfinalizer(final) return test_app
Example #8
Source File: test.py From peewee-db-evolve with GNU Lesser General Public License v3.0 | 5 votes |
def test_circular_deps(self): class SomeModel(pw.Model): some_model2 = DeferredForeignKey('SomeModel2') class Meta: database = self.db class SomeModel2(pw.Model): some_model = pw.ForeignKeyField(SomeModel) class Meta: database = self.db self.evolve_and_check_noop()
Example #9
Source File: test.py From peewee-db-evolve with GNU Lesser General Public License v3.0 | 5 votes |
def DeferredForeignKey(*args): pw.ForeignKeyField(pw.DeferredRelation(*args))
Example #10
Source File: test.py From peewee-db-evolve with GNU Lesser General Public License v3.0 | 5 votes |
def foreign_key(model, **kwargs): if PW3: return pw.ForeignKeyField(model=model, **kwargs) else: return pw.ForeignKeyField(rel_model=model, **kwargs)
Example #11
Source File: peeweedbevolve.py From peewee-db-evolve with GNU Lesser General Public License v3.0 | 5 votes |
def _add_fake_fk_field_hook(): init = pw.ForeignKeyField.__init__ def _init(*args, **kwargs): self = args[0] if 'fake' in kwargs: self.fake = kwargs['fake'] del kwargs['fake'] init(*args, **kwargs) pw.ForeignKeyField.__init__ = _init
Example #12
Source File: peeweedbevolve.py From peewee-db-evolve with GNU Lesser General Public License v3.0 | 5 votes |
def _is_foreign_key(field): return isinstance(field, pw.ForeignKeyField)
Example #13
Source File: test_models.py From aiopeewee with MIT License | 5 votes |
def test_meta_rel_for_model(): class User(Model): pass class Category(Model): parent = ForeignKeyField('self') class Tweet(Model): user = ForeignKeyField(User) class Relationship(Model): from_user = ForeignKeyField(User, related_name='r1') to_user = ForeignKeyField(User, related_name='r2') UM = User._meta CM = Category._meta TM = Tweet._meta RM = Relationship._meta # Simple refs work. assert UM.rel_for_model(Tweet) is None assert UM.rel_for_model(Tweet, multi=True) == [] assert UM.reverse_rel_for_model(Tweet) == Tweet.user assert UM.reverse_rel_for_model(Tweet, multi=True) == [Tweet.user] # Multi fks. assert RM.rel_for_model(User) == Relationship.from_user assert RM.rel_for_model(User, multi=True) == [Relationship.from_user, Relationship.to_user] assert UM.reverse_rel_for_model(Relationship) == Relationship.from_user exp = [Relationship.from_user, Relationship.to_user] assert UM.reverse_rel_for_model(Relationship, multi=True) == exp # Self-refs work. assert CM.rel_for_model(Category) == Category.parent assert CM.reverse_rel_for_model(Category) == Category.parent # Field aliases work. UA = User.alias() assert TM.rel_for_model(UA) == Tweet.user
Example #14
Source File: test_models.py From aiopeewee with MIT License | 5 votes |
def test_related_name_collision(flushdb): class Foo(TestModel): f1 = CharField() with pytest.raises(AttributeError): class FooRel(TestModel): foo = ForeignKeyField(Foo, related_name='f1')
Example #15
Source File: validate.py From slim with zlib License | 5 votes |
def field_class_to_schematics_field(field: peewee.Field) -> BaseType: if isinstance(field, peewee.ForeignKeyField): field = field.rel_field kwargs = {} # 检查是否 require if not ((field.default is not None) or field.null or field.sequence or isinstance(field, peewee.AutoField)): kwargs['required'] = True if field.help_text: kwargs['metadata'] = {'description': field.help_text} if isinstance(field, peewee.IntegerField): return IntType(**kwargs) elif isinstance(field, peewee.FloatField): return FloatType(**kwargs) elif isinstance(field, (PG_JSONField, PG_BinaryJSONField, SQLITE_JSONField)): # 注意 SQLITE_JSONField 是一个 _StringField 所以要提前 return JSONType(**kwargs) # HStore 貌似才应该对应 dict,json可以对应任意类型 # return JSONDictType(StringType, **kwargs) elif isinstance(field, peewee.DateTimeField): return DateTimeType(**kwargs) elif isinstance(field, peewee.DateField): return DateType(**kwargs) elif isinstance(field, peewee._StringField): return StringType(**kwargs) elif isinstance(field, peewee.BooleanField): return BooleanType(**kwargs) elif isinstance(field, peewee.BlobField): return BlobType(**kwargs) elif isinstance(field, PG_ArrayField): field: PG_ArrayField return JSONListType(field_class_to_schematics_field(field._ArrayField__field), **kwargs) # noinspection PyProtectedMember
Example #16
Source File: data_record.py From slim with zlib License | 5 votes |
def fields(self): if not self._fields: self._fields = {} for name, v in self.val._meta.fields.items(): if isinstance(v, peewee.ForeignKeyField): name = '%s_id' % name # foreign key self._fields[name] = v return self._fields
Example #17
Source File: peewee_validates.py From peewee-validates with MIT License | 4 votes |
def convert_field(self, name, field): """ Convert a single field from a Peewee model field to a validator field. :param name: Name of the field as defined on this validator. :param name: Peewee field instance. :return: Validator field. """ if PEEWEE3: field_type = field.field_type.lower() else: field_type = field.db_field pwv_field = ModelValidator.FIELD_MAP.get(field_type, StringField) validators = [] required = not bool(getattr(field, 'null', True)) choices = getattr(field, 'choices', ()) default = getattr(field, 'default', None) max_length = getattr(field, 'max_length', None) unique = getattr(field, 'unique', False) if required: validators.append(validate_required()) if choices: validators.append(validate_one_of([c[0] for c in choices])) if max_length: validators.append(validate_length(high=max_length)) if unique: validators.append(validate_model_unique(field, self.instance.select(), self.pk_field, self.pk_value)) if isinstance(field, peewee.ForeignKeyField): if PEEWEE3: rel_field = field.rel_field else: rel_field = field.to_field return ModelChoiceField(field.rel_model, rel_field, default=default, validators=validators) if isinstance(field, ManyToManyField): return ManyModelChoiceField( field.rel_model, field.rel_model._meta.primary_key, default=default, validators=validators) return pwv_field(default=default, validators=validators)
Example #18
Source File: conftest.py From sanic_crud with MIT License | 4 votes |
def app(request): from peewee import SqliteDatabase, Model, CharField, IntegerField, ForeignKeyField from sanic import Sanic from sanic.log import log from sanic_crud import generate_crud from sanic_crud.config import CrudConfig, ResponseMessages db = SqliteDatabase('tests/test.db') class BaseModel(Model): class Meta: database = db class Job(BaseModel): name = CharField() description = CharField() base_pay = IntegerField() class Person(BaseModel): name = CharField() job = ForeignKeyField(Job, related_name='person_job', null=True) email = CharField() db.create_tables([Person, Job]) job = Job(name='Space garbage man', description='Collects garbage in space', base_pay=15) job2 = Job(name='Space Trucker', description='Transfers things... in space', base_pay=25) person = Person(name='Sanic the Hedgehog', email='gottagofeast@fast.com', job=1) job.save() job2.save() person.save() test_app = Sanic(__name__) test_app.log = log config = CrudConfig response_messages = ResponseMessages response_messages.SuccessOk = "Cool Brah" config.response_messages = response_messages config.COLLECTION_MAX_RESULTS_PER_PAGE = 1 generate_crud(test_app, [Person, Job]) def final(): db.drop_tables([Person, Job]) request.addfinalizer(final) return test_app