How to custom the table name in peewee? - postgresql

I want to define a table which the table name is gobang_server,i write code as follow:
class BaseModel(Model):
class Meta:
database = database
class GobangServer(BaseModel):
time = DateField(default=datetime.datetime.now())
name = CharField(max_length=64)
host = CharField(max_length=30)
port = IntegerField()
pid = IntegerField()
but i look at PostgreSQL the table name is "gobangserver"?
How can i define with the table name is gobang_server and the class name is not be modified.

class GobangServer(BaseModel):
...
class Meta:
db_table = 'gobang_server'
In peewee 3.0 it changes from "db_table" to "table_name".

Related

Django Rest Framework - Serializer error when trying to add model from json with 1 attribute as array

Im trying to create an API with Django RestFramework to save some info of computers.
I have encountered a problem when the json has an attribute that is an array of IPv4 field.
I generated the following code
Model
class Computer(models.Model):
hostname = models.CharField(max_length=32)
os_system = models.CharField(max_length=60)
class ComputerIPAddress(models.Model):
computer = models.ForeignKey(Computer,on_delete=models.CASCADE)
ip_address = models.GenericIPAddressField()
Serializer
class ComputerIPAddressSerializer(serializers.ModelSerializer):
class Meta:
model = ComputerIPAddress
fields = ('__all__')
class ComputerSerializer(serializers.ModelSerializer):
ip_address = ComputerIPAddressSerializer(many=True)
class Meta:
model = Computer
fields = ('__all__')
Viewset
class ComputerViewSet(viewsets.ModelViewSet):
queryset = Computer.objects.all()
serializer_class = ComputerSerializer
class ComputerIPAddressViewSet(viewsets.ModelViewSet):
queryset = ComputerIPAddress.objects.all()
serializer_class = ComputerIPAddressSerializer
The idea is that the IP belongs to the computer (if the computer is deleted, I am not interested in having the IP) and a computer can have several IP assigned to it.
The json that is sent is the following:
{'hostname':'PC-01','os_system':'Windows 10','ip_address':['192.168.1.10','192.168.2.10']}
I would approach this problem by overriding the create method the ComputerSerializer
class ComputerSerializer(serializer.ModelSerializer):
...
def create(self, validated_data):
ip_address = validated_data.pop("ip_address", None)
computer = Computer.objects.create(**validated_data)
if ip_address:
for ip in ip_address:
computer.computeripaddress_set.create(ip)
return computer

How to extend django's default User in mongodb?

I'm using mongodb as database and trying to extend the django's inbuilt user model.
here's the error I'm getting:
django.core.exceptions.ValidationError: ['Field "auth.User.id" of model container:"<class \'django.contrib.auth.models.User\'>" cannot be of type "<class \'django.db.models.fields.AutoField\'>"']
Here's my models.py:
from djongo import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.EmbeddedField(model_container=User)
mobile = models.PositiveIntegerField()
address = models.CharField(max_length=200)
pincode = models.PositiveIntegerField()
Using EmbeddedField is not a good idea, because it will duplicate user data in the database. You will have some user in the Users collection and the same data will be embedded in the Profile collection elements.
Just keep the user id in the model and query separately:
class Profile(models.Model):
user_id = models.CharField() #or models.TextField()
mobile = models.PositiveIntegerField()
address = models.CharField(max_length=200)
pincode = models.PositiveIntegerField()
It is simple as defined in the documentation.
So, first, use djongo models as the model_container, and I suppose the User model is the Django model, not the djongo model.
And the second thing, make your model_cotainer model abstract by defining in the Meta class as given below.
from djongo import models
class Blog(models.Model):
name = models.CharField(max_length=100)
class Meta:
abstract = True
class Entry(models.Model):
blog = models.EmbeddedField(
model_container=Blog
)
headline = models.CharField(max_length=255)
Ref: https://www.djongomapper.com/get-started/#embeddedfield

How can I listen for the creation of a specific model and create a new one (on a different table) based on this?

I have a User model with a referral_key attribute. I'd like to create a ReferralKeyRecord upon creation of a user. I've read tons of documentation and StackExchange to no avail.
This answer uses after_insert(), but I am not trying to alter or validate the class which is being inserted; I am trying to add a new object from a completely different model—and session.add() isn't supported.
This answer is closer to what I want, but the accepted answer (ultimately) uses after_flush(), which is far too general. I don't want to listen to events thrown whenever the DB is updated somehow. I want it to fire off when a specific model is created.
And something like the following...
#event.listens_for(User, 'after_flush')
def create_referral_record(mapper, connection, target):
session.add(ReferralRecord(key=instances.referral_key))
session.commit()
... results in No such event 'after_flush' for target '<class 'models.User'>. I've looked through SQLAlchemy's documentation (the core events and the ORM events) and see no events that indicate a specific model has been created. The closest thing in Mapper events is the after_insert method, and the closest thing in Session events is the after_flush() method. I imagine this is a pretty common thing to need to do, and would thus be surprised if there wasn't an easy event to listen to. I assume it'd be something like:
#event.listens_for(User, 'on_creation')
def create_referral_record(session, instance):
record = ReferralRecord(key=instance.referral_key)
session.add(record)
session.commit()
Does anyone know better than I?
Or why not create the Referral inside the User constructor?
from sqlalchemy.orm import Session, relationship, Mapper
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, ForeignKey, create_engine, event
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
def __init__(self):
self.referral = Referral()
id = Column(Integer(), primary_key=True)
referral = relationship('Referral', uselist=False)
class Referral(Base):
__tablename__ = 'referral'
id = Column(Integer(), primary_key=True)
user_id = Column(Integer(), ForeignKey('user.id'), nullable=False)
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
session = Session(bind=engine)
session.add(User())
session.commit()
print(session.query(User).all())
print(session.query(Referral).all())
You can use the after_flush session event, and inside the event handler you can access the session's new objects (using session.new).
Example:
from sqlalchemy.orm import Session, relationship, Mapper
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, ForeignKey, create_engine, event
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer(), primary_key=True)
class Referral(Base):
__tablename__ = 'referral'
id = Column(Integer(), primary_key=True)
user_id = Column(Integer(), ForeignKey('user.id'), nullable=False)
engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
session = Session(bind=engine)
#event.listens_for(session, 'after_flush')
def session_after_flush(session, flush_context):
for obj in session.new:
if isinstance(obj, User):
session.add(Referral(user_id=obj.id))
session.add(User())
session.commit()
print(session.query(User).all())
print(session.query(Referral).all())
Running this outputs:
[<__main__.User object at 0x00000203ABDF5400>]
[<__main__.Referral object at 0x00000203ABDF5710>]

Is there a way to create objects/ table entries during the extension installation in TYPO3?

I want to create objects during the installation of an extension. For example I have the following two simple domain models:
class Product extends AbstractEntity
{
protected $name = '';
protected $sku = '';
...
}
class Location extends AbstractEntity
{
protected $name = '';
protected $city = '';
...
}
and a third domain model like:
class Mapper extends AbstractEntity
{
protected $domainModelName = '';
protected $domainModelProperty = '';
}
Now I want too add entries like this:
domain_model_name | domain_model_property
Product | name
Product | sku
Location | city
....
during the extension installation or directly after the installation, so that the tx_foxexample_domain_model_mapper table will be filled automatically, is this possible?
I know that I can use a initializeAction, but then the entries will only be generated if I add a plugin and visit the page etc., but I want that the entries/ objects already exists before I use a plugin or add some objects.
You can store your static data in the file ext_tables_static+adt.sql which must be located in the root folder of your extension.
According to the TYPO3 API, you must should use the following command to export your static data
mysqldump --password=[password] [database name] [tablename] --add-drop-table > ./ext_tables_static.sql
Also make sure, that the table structure of static tables is present in the ext_tables.sql file.
The extension static_info_tables makes use of this technique. You can have a look at the extension here for more details.

Lift-mapper - inserting items to database

I am trying to add item to H2 database. My code is:
class Test extends LongKeyedMapper[Test] with IdPK {
def getSingleton = Test
object name extends MappedString(this, 100)
}
and Test.create.name("some_name").id(2).save, but I always get java.lang.Exception: Do not have permissions to set this field. What can I do wrong? Connection is of course open and I have permission to data from database.
IdPK extends MappedLongIndex which is not writable by default, that's why it restricts you from setting the field. Usually you would let the DB generate an PK ID automatically for you via autoincrement field (postgres, mysql), trigger + sequence (oracle), etc. So in most common scenarios you don't need to set this field. To be able to still set it add an override like this on your field:
override def writePermission_? = true