why cannot delete attribute id of model?

35 views
Skip to first unread message

Xudong Zhang

unread,
Jan 11, 2016, 5:07:37 AM1/11/16
to Django users
I want to delete the id attribute of a model but failed, it comlains that the model has no attribute 'id'. But I use hasattr() checked it and it does has the attribute.

My sample code

    product = Product.objects.get(pk=_id)
    if hasttr(product, 'id'):
        del product.id

I also tried delattr(product, 'id'), got same result.

Exception Type: AttributeError
Exception Value:
'Product' object has no attribute 'id'

I use python 3 and django 1.8.

Anyone could help here?

Vijay Khemlani

unread,
Jan 11, 2016, 7:28:11 AM1/11/16
to django...@googlegroups.com
I usually do 

product.id = None
product.pk = None

But I'm not sure whether that's the best way to do it

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/75e6687d-d7fe-4681-ba30-8ed74044a03e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tony Flury

unread,
Jan 11, 2016, 7:35:57 AM1/11/16
to Django users
Why do you want to delete the id field. The idea of a primary key field is central to relational databases. If you to suppress the automatically generated primary key then you need to assign another field as the unique primary key: as far as I know that will prevent the id field being created.

Vijay Khemlani

unread,
Jan 11, 2016, 7:46:18 AM1/11/16
to django...@googlegroups.com
At least I use it as part of the process to save a copy of an existing model instance

On Mon, Jan 11, 2016 at 9:35 AM, Tony Flury <anthon...@btinternet.com> wrote:
Why do you want to delete the id field. The idea of a primary key field is central to relational databases. If you to suppress the automatically generated primary key then you need to assign another field as the unique primary key: as far as I know that will prevent the id field being created.
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

Tony Flury

unread,
Jan 11, 2016, 9:41:13 AM1/11/16
to Django users
Stating the value of either the id or pk field to None is the recommended way to rest the primary key when you take a copy of a record, but Xudong wanted to delete the field entirely: which I don't understand.
Reply all
Reply to author
Forward
0 new messages