开发者

Django delete object which has a string as a primary key

开发者 https://www.devze.com 2023-02-13 08:45 出处:网络
I have the following model class Staff(models.Model): username = models.OneToOneField(Person, primary_key=True)

I have the following model

class Staff(models.Model):
    username = models.OneToOneField(Person, primary_key=True)
    room = models.CharField(blank=True开发者_运维百科, max_length=12)

When I run the following code I get the error Truncated incorrect DOUBLE value: 'lacc1'

s = Staff.objects.get(pk = 'lacc1').delete()

I assume this has something to do with the primary key being a string. Does anyone know how I can solve this problem.

It is only on deletes. If I just want to get the object using get or filter it works fine. There is also a object in the db with pk lacc1 so that is not the problem.

EDIT

Person Class

class Person(models.Model):
    username = models.CharField(primary_key=True, max_length=12)
    title = models.CharField(max_length=25)
    forenames = models.CharField(max_length=50)
    surname =  models.CharField(max_length=50)


Your primary key is not a string, it's an int.

username = models.OneToOneField(Person, primary_key=True)

username here is not a CharField but a OneToOneField, meaning a relation to a Person object model, meaning a field containing the id of the row of this person instance in the person table.

You may want to rename it this way:

person = models.OneToOneField(Person, primary_key=True)

And, assuming your Person object has a usernameattribute, you can delete your staff this way:

s = Staff.objects.get(person__username='lacc1').delete()

However, you must know that this implies a JOIN on the person_id field and a filter on a the Staff username field, which is probably not indexed. It will be slower than what you expected, but I doubt it should ba any trouble.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号