I work with models in jango, it took a cycle

forwarder = Forwarder.objects.all() sum_forwarders = forwarder.count() for i in range(sum_forwarders): current_forwarder = Forwarder.objects.get(id=i).proj.all() 

But I get an error

 bot.models.DoesNotExist: Forwarder matching query does not exist. 

The bottom line is that I created an element, django assigned id=1

After removing the element id=1 , None is formed in its place.

And when creating a new one, it will already be under id=2 , and id=1 will remain with the value None

Can you please tell me in which way I can update this, or in what way can I go through a cycle starting with values ​​that have the correct id?

And anyway, why does everything happen in exactly this way? Why doesn't django delete an item along with its id?

  • The essence of identifiers in their constancy, they can not be changed. Why use such a perverted workaround? Why not for forwarder in Forwarder.objects.all() ? - Sergey Gornostaev
  • @SergeyGornostaev because I have the M2M field and I cannot access its elements if I use another method - Milkiweed Gtlt
  • You can, the m2m field does not change anything. - Sergey Gornostaev

1 answer 1

And anyway, why does everything happen in exactly this way? Why doesn't django delete an item along with its id?

Django ORM is only an interface for communicating with the database, the id field behaves this way because it has this behavior in the SQL query "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT

Can you please tell me in which way I can update this, or in what way can I go through a cycle starting with values ​​that have the correct id?

There is no need to update anything, you simply "incorrectly" make queries to the database. The request should look something like this:

 forwarders = Forwarder.objects.all() for forwarder in forwarders: # делать что то 

To add m2m fields to the QuerySet, you can use the prefetch_related () method

 forwarders = Forwarder.objects.all().prefetch_related('имя поля')