0

I'm writing a django website with a sqlite database, I have a model in my website like this :

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
   return self.question_text
def was_published_recently(self):
   return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

Suppose I create Question object "What's up" and delete it and now create another Question object "HI" then "Hi" will get the id 2 not 1.But I want it to be 1 only.Is this possible? I m using django 1.8.7 and can't change the version as whole database is written in django 1.8.7.

  >> f = Question(question_text="What's up",pub_date=timezone.now())
    >> f.id
       1
    >> f.delete()
    >> g = Question(question_text="Hi",pub_date=timezone.now())
    >> g.id
       2

Any help will be appreciated.Thanks in advance

  • Any particular reason to want this behaviour? This would probably cause problems with deletes and foreign keys if cascade is not used – Shaumux Jan 30 '18 at 13:06
  • Actually I have set urls such that i m passing id as one of my parameter so webpage are associated in that way.So somebody if wanted to access the webpage so if he/she hits ip/index/ number that page will open but as I have made lot of changes so urls are not in increment form. – Vaibhav Goyal Jan 30 '18 at 13:10
  • 1
    You're opening this up for multipe things to go wrong, if somebody bookmarks a page and that page gets deleted, they'll end up on a different page, this is a security nightmare, specially if the pages are supposed to be access protected, the whole point of that kind of url scheme is that , the urls would be permanent and unique for each resource, if a page or resource is deleted, the person should get a 404 – Shaumux Jan 30 '18 at 13:17
  • You're absolutely right no doubt in that but in development phase i wanted to do this not after launching it so the problem you stated will not be a problem indeed :) – Vaibhav Goyal Jan 30 '18 at 13:33
  • In raw SQLite, you would have to [drop the AUTOINCREMENT keyword](http://www.sqlite.org/autoinc.html). I don't know how to do this in Django. – CL. Jan 30 '18 at 13:58
  • https://stackoverflow.com/questions/1601697/sqlite-reset-primary-key-field – trinchet Jan 30 '18 at 14:29

1 Answers1

0

You can do something like this

class Question(models.Model):
    id = models.IntegerField(primary_key=True)
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

override save and check the the last available id in the table and incerment by and assign to id. Though I wouldn't recommend doing this even in dev, seen a lot of code meant for dev only go in prod, just because somebody forgot to remove it

Shaumux
  • 735
  • 11
  • 25