V
V
Vitaly2015-09-28 08:42:56
Django
Vitaly, 2015-09-28 08:42:56

How to make a record in the db on a Django condition?

Hello, after submitting a form with a POST request, the data is written to the database. I need to implement a record by condition, in case there is no such record in the database (simultaneously 2 conditions).
What I would like to know:
1. How to make it so that save () when writing to the database does a check like in SQL, whether there is such data already in the database. If not, we write, if yes, we display an error message.
2. Separately, make a request to count how many values ​​the records "A" (1, 2 .. 10 records) have, only the number. And write this number into a variable
3. (At the request of the sensei) Explain what is more correct (faster!), when we write the stock data to the database and do not bother, and then count them (as in SQL through grouping) Or check, so as not to produce garbage, this is the opposite, the right decision. (note the number is about 100K lines)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2015-09-28
@allposts_vitali

Make it so that save() when writing to the database does a check like in SQL and whether such data is already in the database. If not, we write, if yes, we display an error message.
https://docs.djangoproject.com/en/1.8/ref/models/f...
https://docs.djangoproject.com/en/1.8/topics/db/ag...
# Each publisher, each with a count of books as a "num_books" attribute.
>>> from django.db.models import Count
>>> pubs = Publisher.objects.annotate(num_books=Count('book'))
>>> pubs
[<Publisher BaloneyPress>, <Publisher SalamiPress>, ...]
>>> pubs[0].num_books
73

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question