#Django_ORM
Make model save only one object
`class Origin(models.Model):
name = models.CharField(max_length=100)
def save(self, *args, **kwargs):
if self.class.objects.count():
self.pk = self.class.objects.first().pk
super().save(*args, **kwargs)`
Make model save only one object
`class Origin(models.Model):
name = models.CharField(max_length=100)
def save(self, *args, **kwargs):
if self.class.objects.count():
self.pk = self.class.objects.first().pk
super().save(*args, **kwargs)`
#Django_ORM #Models
Signals vs Overriding .save
—If your fields depend on a model you control, override .save
—If your fields depend on a model from a 3rd party app, which you do no control, use signals.
Signals vs Overriding .save
—If your fields depend on a model you control, override .save
—If your fields depend on a model from a 3rd party app, which you do no control, use signals.
#Django_ORM #ordering
Order queryset by case insensitive manner
Order queryset by case insensitive manner
User.objects.all().order_by(Lower('username'))#Django_ORM #Database
Convert existing databases to Django models
or
Convert existing databases to Django models
python manage.py inspectdbor
python manage.py inspectdb > models.py#Django_ORM #Database
Rename column name in Database Table:
` a = models.CharField(max_length=40,db_column='column1')`
Rename column name in Database Table:
` a = models.CharField(max_length=40,db_column='column1')`
Note!!!
Use comments liberally not just for yourself, but for anyone else who might have to maintain or enhance your code in the future!!
Use comments liberally not just for yourself, but for anyone else who might have to maintain or enhance your code in the future!!
SearchVector
For searching several fields by annotating to one field
For searching several fields by annotating to one field
>> from django.contrib.postgres.search import SearchVector
>>> Entry.objects.annotate(
... search=SearchVector('body_text', 'blog__tagline'),
... ).filter(search='Cheese')
[<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]
#working_with_files
Title: Reading Files
Builtin operator
instead of :
can use:
Title: Reading Files
Builtin operator
with in python will automatically close the file when you are done processing it.instead of :
handle = open("test.txt")can use:
with open("test.txt") as file_handlerClean Code Principles
✅Code should be elegant and pleasing to read.
✅No duplication should be allowed. Use DRY (Don't Repeat Yourself)
✅Code should be covered with tests.
✅Every function should do one thing and do it well.
✅Codebase should contain only code that is needed.
✅Code should be elegant and pleasing to read.
✅No duplication should be allowed. Use DRY (Don't Repeat Yourself)
✅Code should be covered with tests.
✅Every function should do one thing and do it well.
✅Codebase should contain only code that is needed.