import json
data = {'0': 1, '4': 2}
instance.field_name = json.dumps(data)
instance.save()
from django.contrib.postgres.fields import JSONField
from django.db import models
class CustomModel(models.Model):
json_field_name = JSONField()
instance = CustomModel()
instance.field_name = {'0': 1, '4': 2}
instance.save()
data = [{'0': 4}, {'4': 2}]
from django.urls import include, re_path
urlpatterns = [
re_path(r'^(?P<catalog>\w+)/$', views.catalog_view, name='catalog'),
re_path(r'^(?P<catalog>\w+)/(?P<brand>\w+)/$', views.brand_view, name='brand'),
re_path(r'^(?P<catalog>\w+)/(?P<brand>\w+)/(?P<product>\w+)/$', views.product_view, name='product'),
...
]
def product_view(request, catalog, brand, product):
# ...
class ImagesForSliderSerializer(serializers.ModelSerializer):
class Meta:
model = ImagesForSlider
fields = ('id', 'image', 'image_name')
class GroupSerializer(serializers.ModelSerializer):
images_for_slider = ImagesForSliderSerializer(many=True)
class Meta:
model = Group
fields = (
# ...
'images_for_slider',
)
Как инкрементировать дату в python?
from datetime import datetime, timedelta
some_date = datetime(year=2018, month=10, day=30)
delta_some_date = some_date + timedelta(days=5)
print(delta_some_date)
class AdvertDetailView(DetailView):
model = Advert
template_name = "advert/_detail.html"
context_object_name = "advert"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
advert_fields = []
for field in self.model._meta.fields:
advert_fields.append((field.verbose_name, str(getattr(self.object, field.name))))
context['advert_fields'] = advert_fields
return context
<ul>
{% for verbose_name, value in advert_fields %}
<li>{{ verbose_name }} -> {{ value }}</li>
{% endfor %}
</ul>
_band_form = BandForm(request.POST, instance=user)
- здесь задается instance модели User, а нужен Band.user = User()
- несохраненный инстанс юзера бесполезно указывать как ForeignKey для Band. Необходимо его самого сначала сохранить The deprecated functions expm2 and expm3 have been removed from scipy.linalg. The deprecated keyword q was removed from scipy.linalg.expm. And the deprecated submodule linalg.calc_lwork was removed.
pip install scipy==0.9.0
filter_map = {}
def set_if_not_none(mapping, key, value):
if value is not None and value is not '' and key != 'order_by':
mapping['{}__iexact'.format(key)] = value
for req_key, req_value in dict(request.GET).items():
set_if_not_none(filter_map,req_key,req_value[0])
debtors_list = Debtors.objects.filter(**filter_map).order_by(ordering)
def find_id(document):
with open(document) as fp:
soup = BeautifulSoup(fp, "lxml")
find_p = soup.find("p", {"class": "five"})
text = find_p.get_text(strip=True) if find_p else ''
if ':' in text:
return text.split(':')[-1].strip()
# возвратить пустую строку или рейзить ошибку или что-то другое
return ''
# Выбрать все объекты load за дату
loads = Load.objects.filter(date=datetime.now())
# цикл по loads, в каждой итерации еще цикл с получением значений для rent_id
[i.values_list('rent_id', flat=True) \
for i in [load.loadpara_set.all() for load in loads] if i]
list(LoadPara.objects.filter(load__date=datetime.now().date()).values_list('rent_id', flat=True))