OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Failed to Create a new data in a joined table inheritance in Flask

  • Thread starter Thread starter Zidan Albaihaqi
  • Start date Start date
Z

Zidan Albaihaqi

Guest
Currently im developing a website using flask as the backend and i got kind of stuck in thi problem. So i'm developing a function to create a new data. For clearer understanding, this is how i illustrate the model of the related data

  • KekayaanIntelektual is the parent model (and table) for HakCipta and Paten
  • KekayaanIntelektual has many to many relationship with Inventor, Pemegang, RiwayatKerjaSama

The function i create is for HakCipta model, and this is the model

Code:
from exts import db
import uuid
from models import KekayaanIntelektual

class HakCipta(KekayaanIntelektual):
    __tablename__ = 'hak_cipta'
    ID_KI = db.Column(db.String(36), db.ForeignKey('kekayaan_intelektual.ID_KI'), primary_key=True)
    
    NO_PENCATATAN = db.Column(db.String(50), nullable=True)
    TGL_PENCATATAN = db.Column(db.DateTime, nullable=True)
    JENIS_CIPTAAN = db.Column(db.String(25), nullable=True)

    __mapper_args__ = {
        'polymorphic_identity': 'hak_cipta',
    }

and this is the model for KekayaanIntelektual

Code:
from exts import db
from models import has_ki
from models import create_ki
import uuid

class KekayaanIntelektual(db.Model):
    __tablename__ = 'kekayaan_intelektual'
    ID_KI = db.Column(db.String(36), primary_key=True, default=str(uuid.uuid4))
    NO_PERMOHONAN_KI = db.Column(db.String(50), nullable=True)
    TGL_PERMOHONAN = db.Column(db.DateTime, nullable=True)
    JUDUL = db.Column(db.String(50), nullable=False)
    ABSTRAK = db.Column(db.Text, nullable=False)
    TGL_AWAL_PERLINDUNGAN = db.Column(db.DateTime, nullable=True)
    TGL_AKHIR_PERLINDUNGAN = db.Column(db.DateTime, nullable=True)
    STATUS = db.Column(db.String(20), nullable=False)
    JENIS_KI = db.Column(db.String(50), nullable=False)

    pemegangs = db.relationship('Pemegang', secondary='has_ki', backref=db.backref('kekayaan_intelektual', lazy=True))
    form_ketertarikan = db.relationship('FormKetertarikan', backref='form_ketertarikan', lazy=True)
    riwayat_kerja_sama = db.relationship('RiwayatKerjaSama', backref='riwayat_kerja_sama', lazy=True)
    gambar_ki = db.relationship('GambarKi', backref='gambar_ki', lazy=True)
    inventors = db.relationship('Inventor', secondary='create_ki', lazy='subquery', backref=db.backref('kekayaan_intelektual', lazy=True))
    hak_cipta = db.relationship('HakCipta', backref=db.backref('kekayaan_intelektual', lazy=True))

    __mapper_args__ = {
        'polymorphic_on': JENIS_KI,
        'polymorphic_identity': 'kekayaan_intelektual',
        'with_polymorphic': '*'
    }

and this is the function

Code:
def post(self):
        data = request.get_json()
        
        try:
            print("Received data:", data)
            
         
            new_hak_cipta = HakCipta(
                NO_PERMOHONAN_KI=data.get('NO_PERMOHONAN_KI'),
                TGL_PERMOHONAN=parse_date(data.get('TGL_PERMOHONAN')),
                JUDUL=data['JUDUL'],
                ABSTRAK=data.get('ABSTRAK'),
                TGL_AWAL_PERLINDUNGAN=parse_date(data.get('TGL_AWAL_PERLINDUNGAN')),
                TGL_AKHIR_PERLINDUNGAN=parse_date(data.get('TGL_AKHIR_PERLINDUNGAN')),
                STATUS=data.get('STATUS'),
                JENIS_KI='hak_cipta',  # Set the type here if needed
                # 
                ID_KI = str(generate_uuid()),
                NO_PENCATATAN=data.get('NO_PENCATATAN'),
                TGL_PENCATATAN=parse_date(data.get('TGL_PENCATATAN')),
                JENIS_CIPTAAN=data.get('JENIS_CIPTAAN')
            )
            # new_hak_cipta.hak_cipta.append(new_hak_cipta)

            # Add related entities
            if 'pemegangs' in data:
                pemegangs = Pemegang.query.filter(Pemegang.ID_PEMEGANG.in_(data['pemegangs'])).all()
                # ki.pemegangs.extend(pemegangs)
                new_hak_cipta.pemegangs.extend(pemegangs)

            if 'inventors' in data:
                inventors = Inventor.query.filter(Inventor.NIP_NIM.in_(data['inventors'])).all()
                # ki.inventors.extend(inventors)
                new_hak_cipta.inventors.extend(inventors)

            if 'riwayat_kerja_sama' in data:
                for rks_data in data['riwayat_kerja_sama']:
                    rks = RiwayatKerjaSama(
                        ID_KERJA_SAMA=str(generate_uuid()),
                        TGL_MULAI=parse_date(rks_data.get('TGL_MULAI')),
                        TGL_AKHIR=parse_date(rks_data.get('TGL_AKHIR')),
                        NAMA_INSTITUSI=rks_data['NAMA_INSTITUSI'],
                        ALAMAT=rks_data.get('ALAMAT'),
                        NEGARA=rks_data.get('NEGARA'),
                        DESKRIPSI=rks_data.get('DESKRIPSI'),
                        LOGO_DIR=rks_data.get('LOGO_DIR'),
                        # ID_KI=ki.ID_KI
                    )
                    new_hak_cipta.riwayat_kerja_sama.extend(rks)

            # Add and commit the HakCipta object
            db.session.add(new_hak_cipta)
            print("added hak cipta")
            db.session.commit()
            print("comitted")

            return {
                'message': 'Hak Cipta created successfully',
                'data': new_hak_cipta
            }, 201

        except Exception as e:
            db.session.rollback()
            error_message = str(e)
            traceback.print_exc()
            return {'message': 'An unexpected error occurred: ' + error_message}, 500

i try to insert this data

Code:
{
"NO_PERMOHONAN_KI": "1",
"TGL_PERMOHONAN": "2024-06-14 14:38:48",
"JUDUL": "Buku Tatang Sutarman",
"ABSTRAK": "Tatang Sutarman adalah seorang filosofis",
"TGL_AWAL_PERLINDUNGAN": "2024-06-14 14:38:48",
"TGL_AKHIR_PERLINDUNGAN": "2024-06-14 14:38:48",
"STATUS": "Diterima",
"JENIS_KI": "hak_cipta",
"pemegangs": [
"1"
],
"inventors": [
"201524033", "201524054"
],
"NO_PENCATATAN":"NP01",
"TGL_PENCATATAN":"2024-06-20",
"JENIS_CIPTAAN":"Buku"
}

but im getting this error sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1364, "Field 'JUDUL' doesn't have a default value")

Code:
[SQL: INSERT INTO hak_cipta (`ID_KI`, `NO_PENCATATAN`, `TGL_PENCATATAN`, `JENIS_CIPTAAN`) VALUES (%(ID_KI)s, %(NO_PENCATATAN)s, %(TGL_PENCATATAN)s, %(JENIS_CIPTAAN)s)] 
[parameters: {'ID_KI': 'c349df13-9a90-4883-badf-526540f5cfa1', 'NO_PENCATATAN': 'NP01', 'TGL_PENCATATAN': datetime.datetime(2024, 6, 20, 0, 0), 'JENIS_CIPTAAN': 'Buku'}]
(Background on this error at: https://sqlalche.me/e/20/e3q8)

why am i getting this error? i thought when i create HakCipta and then the instance of KekayaanIntelektual is also generated.
<p>Currently im developing a website using flask as the backend and i got kind of stuck in thi problem. So i'm developing a function to create a new data. For clearer understanding, this is how i illustrate the model of the related data</p>
<ul>
<li>KekayaanIntelektual is the parent model (and table) for HakCipta and Paten</li>
<li>KekayaanIntelektual has many to many relationship with Inventor, Pemegang, RiwayatKerjaSama</li>
</ul>
<p>The function i create is for HakCipta model, and this is the model</p>
<pre><code>from exts import db
import uuid
from models import KekayaanIntelektual

class HakCipta(KekayaanIntelektual):
__tablename__ = 'hak_cipta'
ID_KI = db.Column(db.String(36), db.ForeignKey('kekayaan_intelektual.ID_KI'), primary_key=True)

NO_PENCATATAN = db.Column(db.String(50), nullable=True)
TGL_PENCATATAN = db.Column(db.DateTime, nullable=True)
JENIS_CIPTAAN = db.Column(db.String(25), nullable=True)

__mapper_args__ = {
'polymorphic_identity': 'hak_cipta',
}


</code></pre>
<p>and this is the model for KekayaanIntelektual</p>
<pre><code>from exts import db
from models import has_ki
from models import create_ki
import uuid

class KekayaanIntelektual(db.Model):
__tablename__ = 'kekayaan_intelektual'
ID_KI = db.Column(db.String(36), primary_key=True, default=str(uuid.uuid4))
NO_PERMOHONAN_KI = db.Column(db.String(50), nullable=True)
TGL_PERMOHONAN = db.Column(db.DateTime, nullable=True)
JUDUL = db.Column(db.String(50), nullable=False)
ABSTRAK = db.Column(db.Text, nullable=False)
TGL_AWAL_PERLINDUNGAN = db.Column(db.DateTime, nullable=True)
TGL_AKHIR_PERLINDUNGAN = db.Column(db.DateTime, nullable=True)
STATUS = db.Column(db.String(20), nullable=False)
JENIS_KI = db.Column(db.String(50), nullable=False)

pemegangs = db.relationship('Pemegang', secondary='has_ki', backref=db.backref('kekayaan_intelektual', lazy=True))
form_ketertarikan = db.relationship('FormKetertarikan', backref='form_ketertarikan', lazy=True)
riwayat_kerja_sama = db.relationship('RiwayatKerjaSama', backref='riwayat_kerja_sama', lazy=True)
gambar_ki = db.relationship('GambarKi', backref='gambar_ki', lazy=True)
inventors = db.relationship('Inventor', secondary='create_ki', lazy='subquery', backref=db.backref('kekayaan_intelektual', lazy=True))
hak_cipta = db.relationship('HakCipta', backref=db.backref('kekayaan_intelektual', lazy=True))

__mapper_args__ = {
'polymorphic_on': JENIS_KI,
'polymorphic_identity': 'kekayaan_intelektual',
'with_polymorphic': '*'
}

</code></pre>
<p>and this is the function</p>
<pre><code>def post(self):
data = request.get_json()

try:
print("Received data:", data)


new_hak_cipta = HakCipta(
NO_PERMOHONAN_KI=data.get('NO_PERMOHONAN_KI'),
TGL_PERMOHONAN=parse_date(data.get('TGL_PERMOHONAN')),
JUDUL=data['JUDUL'],
ABSTRAK=data.get('ABSTRAK'),
TGL_AWAL_PERLINDUNGAN=parse_date(data.get('TGL_AWAL_PERLINDUNGAN')),
TGL_AKHIR_PERLINDUNGAN=parse_date(data.get('TGL_AKHIR_PERLINDUNGAN')),
STATUS=data.get('STATUS'),
JENIS_KI='hak_cipta', # Set the type here if needed
#
ID_KI = str(generate_uuid()),
NO_PENCATATAN=data.get('NO_PENCATATAN'),
TGL_PENCATATAN=parse_date(data.get('TGL_PENCATATAN')),
JENIS_CIPTAAN=data.get('JENIS_CIPTAAN')
)
# new_hak_cipta.hak_cipta.append(new_hak_cipta)

# Add related entities
if 'pemegangs' in data:
pemegangs = Pemegang.query.filter(Pemegang.ID_PEMEGANG.in_(data['pemegangs'])).all()
# ki.pemegangs.extend(pemegangs)
new_hak_cipta.pemegangs.extend(pemegangs)

if 'inventors' in data:
inventors = Inventor.query.filter(Inventor.NIP_NIM.in_(data['inventors'])).all()
# ki.inventors.extend(inventors)
new_hak_cipta.inventors.extend(inventors)

if 'riwayat_kerja_sama' in data:
for rks_data in data['riwayat_kerja_sama']:
rks = RiwayatKerjaSama(
ID_KERJA_SAMA=str(generate_uuid()),
TGL_MULAI=parse_date(rks_data.get('TGL_MULAI')),
TGL_AKHIR=parse_date(rks_data.get('TGL_AKHIR')),
NAMA_INSTITUSI=rks_data['NAMA_INSTITUSI'],
ALAMAT=rks_data.get('ALAMAT'),
NEGARA=rks_data.get('NEGARA'),
DESKRIPSI=rks_data.get('DESKRIPSI'),
LOGO_DIR=rks_data.get('LOGO_DIR'),
# ID_KI=ki.ID_KI
)
new_hak_cipta.riwayat_kerja_sama.extend(rks)

# Add and commit the HakCipta object
db.session.add(new_hak_cipta)
print("added hak cipta")
db.session.commit()
print("comitted")

return {
'message': 'Hak Cipta created successfully',
'data': new_hak_cipta
}, 201

except Exception as e:
db.session.rollback()
error_message = str(e)
traceback.print_exc()
return {'message': 'An unexpected error occurred: ' + error_message}, 500

</code></pre>
<p>i try to insert this data</p>
<pre><code>{
"NO_PERMOHONAN_KI": "1",
"TGL_PERMOHONAN": "2024-06-14 14:38:48",
"JUDUL": "Buku Tatang Sutarman",
"ABSTRAK": "Tatang Sutarman adalah seorang filosofis",
"TGL_AWAL_PERLINDUNGAN": "2024-06-14 14:38:48",
"TGL_AKHIR_PERLINDUNGAN": "2024-06-14 14:38:48",
"STATUS": "Diterima",
"JENIS_KI": "hak_cipta",
"pemegangs": [
"1"
],
"inventors": [
"201524033", "201524054"
],
"NO_PENCATATAN":"NP01",
"TGL_PENCATATAN":"2024-06-20",
"JENIS_CIPTAAN":"Buku"
}

</code></pre>
<p>but im getting this error
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1364, "Field 'JUDUL' doesn't have a default value")</p>
<pre><code>[SQL: INSERT INTO hak_cipta (`ID_KI`, `NO_PENCATATAN`, `TGL_PENCATATAN`, `JENIS_CIPTAAN`) VALUES (%(ID_KI)s, %(NO_PENCATATAN)s, %(TGL_PENCATATAN)s, %(JENIS_CIPTAAN)s)]
[parameters: {'ID_KI': 'c349df13-9a90-4883-badf-526540f5cfa1', 'NO_PENCATATAN': 'NP01', 'TGL_PENCATATAN': datetime.datetime(2024, 6, 20, 0, 0), 'JENIS_CIPTAAN': 'Buku'}]
(Background on this error at: https://sqlalche.me/e/20/e3q8)
</code></pre>
<p>why am i getting this error? i thought when i create HakCipta and then the instance of KekayaanIntelektual is also generated.</p>
 

Latest posts

I
Replies
0
Views
1
impact christian
I
Top