class ClientAccessAccount(models.Model):
client = models.OneToOneField(Client, models.DO_NOTHING, primary_key=True)
account = models.ForeignKey(Account, models.DO_NOTHING)
recent_access_date = models.DateField(blank=True, null=True)
def __str__(self) -> str:
return self.account.account_id
class Meta:
managed = False
db_table = 'client_access_account'
constraints = [
models.UniqueConstraint(
fields=['client', 'account'], name='unique_client_account'
)
]
it’s model generated by inspectdb
from existing MySQL database.
The underlying relationship is that one client can access many accounts and one account can be accessed by many clients. So I think it’s a many to many relationship and the SQL tables is the following code.
create table client_access_account
(
client_id varchar(18) not null,
account_id varchar(10) not null,
recent_access_date date,
primary key (client_id, account_id)
);
I use py manage.py inspectdb
to get the code above and modify the meta constraints from unique_together
to UniqueConstraint
after seeing python - How can I set two primary key fields for my models in Django? - Stack Overflow
My Question is that when I use ClientAccessAccount.objects.create(client=client, account=account, ...)
to create the record that client A access another account C when client accessed account B before, I get Duplicate Entry
error, saying that client A already has an account.
when use full_clean
to validate the model, I also get this error.
How to solve the problem?