I have an issue with my django model, basically with the primary keys.
I use the admin interface to manage my data. I have set up a database that consists of 3 primary keys to reduce multiple entries (year
, month
, bnr
).
But I don't get this covered in my model, as django only accept one primary key. I have tried out a few things but none where helpful for me. The Admin Interface gives me an error all the time.
- Removing all primary keys in my model
- Tried to add an ID Column in my model/Database but not declared as primary key in my DB
- added
unique_together
Right now my model looks like this:
class BalBalance(models.Model):
month = models.PositiveIntegerField(default=datetime.datetime.now().month, validators=[MinValueValidator(1), MaxValueValidator(12)])
year = models.PositiveIntegerField(default=datetime.datetime.now().year, validators=[MinValueValidator(1990), MaxValueValidator(datetime.datetime.now().year)])
bnr = models.ForeignKey('BalBankaccount', models.DO_NOTHING, db_column='BNR') # Field name made lowercase.
balance = models.DecimalField(db_column='BALANCE', max_digits=10, decimal_places=2) # Field name made lowercase.
available_balance = models.DecimalField(db_column='AVAILABLE_BALANCE', max_digits=10, decimal_places=2) # Field name made lowercase.
unavailable_balance = models.DecimalField(db_column='UNAVAILABLE_BALANCE', max_digits=10, decimal_places=2) # Field name made lowercase.
date_checked = models.DateTimeField(db_column='DATE_CHECKED') # Field name made lowercase.
created_at = models.DateTimeField(db_column='CREATED_AT') # Field name made lowercase.
class Meta:
managed = False
db_table = 'BAL_BALANCE'
unique_together = (('month', 'year', 'bnr'),)
and my admin.py looks like this
from django.contrib import admin
from .models import *
# Register your models here.
myModels = [BalBankaccount,BalCompany,BalIncome,BalInstitution,BalLocation]
admin.site.register(myModels)
class BalBalanceAdmin(admin.ModelAdmin):
list_display = ('month','year','bnr','balance','available_balance','unavailable_balance')
list_filter = ('bnr',)
ordering = ('year','month')
search_fields = ('bnr',)
admin.site.register(BalBalance,BalBalanceAdmin)
How can i get rid of this issue? Any help is appreciated
Edit: Depending of what is in place or what I have tested, django throws different errors:
If I declare the primary_key
by my own I get something like:
get() returned more than one BalBalance -- it returned 12!.
Get only allows to return 1 object but in this case it returns 12 objects, because I am not allowed to declare my 3 PK as PK in django...
If I try to deal with this error by adding an ID, django throws me an error that field ID either is missing or has an Integrity Error:
IntegrityError at /admin/balance/balbalance/add/ (1364, "Field 'ID'
doesn't have a default value")
question from:
https://stackoverflow.com/questions/65952441/django-3-primary-key-issues