Hello mates. I have an project with patient laboratory analyses. The problem is my hardcoding but i didn't find the solution to make it simplier.
My aim was to make a dataframe for each analysis group and draw chartjs. So let me explain what i did /w code:
I have a patient analysis model:
class PatientAnalysis(models.Model):
patient = models.ForeignKey(Patient, related_name='analyses', on_delete=models.CASCADE)
analysis_date = models.DateTimeField(default=datetime.now, help_text = "Разделяйте даты точками! Используйте '/' или '-'")
# analysis_type = models.IntegerField(choices = ANALYSIS_CHOICES) #перевести в таблицу
analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1)
analysis_data = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return f"{self.patient}"
def get_analysis_type(self):
return f"{self.analysis_type}"
def get_absolute_url(self):
return reverse('journal:patient_all_info', kwargs={'hist_num_slug':self.patient.pk})
class Meta:
unique_together = ('analysis_date','analysis_type',)
It has analysis type:
class AnalysisType(models.Model):
a_name = models.CharField(max_length=16)
a_measur = models.CharField(max_length=16)
a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
analysis_group = models.ManyToManyField(AnalysysGroup)
def __str__(self):
return f"{self.a_name}"
Which comes with Analysis group:
class AnalysysGroup(models.Model):
group_name = models.CharField(max_length=32)
# analysis = models.ManyToManyField(AnalysisType, blank=True)
def __str__(self):
return f"{self.group_name}"
I tried to show analyses for 1 person for each day and group it by type then draw chartjs multi table:
def patient_filtered_analysis(request, pk, ag):
patient_info = Patient.objects.get(pk=pk)
analysis_group_list = AnalysysGroup.objects.all()
analysis_group = AnalysysGroup.objects.filter(id=ag)[0]
analysis_types_in_group = AnalysisType.objects.filter(analysis_group=ag)
patient_filtered_analysis = PatientAnalysis.objects.filter(patient__hist_num=pk).filter(analysis_type__analysis_group=ag).order_by('analysis_type','-analysis_date')
analysis_date_list = PatientAnalysis.objects.filter(patient__hist_num=pk).filter(analysis_type__analysis_group=ag).order_by('analysis_date').values_list('analysis_date').exclude(analysis_data=0.00).distinct()
query_set = PatientAnalysis.objects.filter(patient__hist_num=pk).filter(analysis_type__analysis_group=ag).order_by('analysis_date').exclude(analysis_data=0.00).distinct()
d = {}
d_nodate = {}
d_forDF = {}
print(analysis_types_in_group)
for analysis_type in analysis_types_in_group:
try:
dates = []
an_rec_for_type_by_day= []
an_rec_forDF = []
for date in analysis_date_list:
try:
checkdate = date[0]
dates.append(checkdate)
analysises = PatientAnalysis.objects.filter(patient__hist_num=pk).filter(analysis_type=analysis_type).filter(analysis_date=checkdate)[0]
if analysises.analysis_data == 0:
an_rec_for_type_by_day.append('N/A')
an_rec_forDF.append('')
elif analysises.analysis_data == 0.00:
an_rec_for_type_by_day.append('N/A')
an_rec_forDF.append('')
else:
if analysises.analysis_data > analysis_type.a_ref_max:
an_rec_for_type_by_day.append(analysises.analysis_data)
an_rec_forDF.append(f"{analysises.analysis_data} *Выс.")
elif analysises.analysis_data < analysis_type.a_ref_min:
an_rec_for_type_by_day.append(analysises.analysis_data)
an_rec_forDF.append(f"{analysises.analysis_data} *Низ.")
else:
an_rec_for_type_by_day.append(analysises.analysis_data)
an_rec_forDF.append(analysises.analysis_data)
except:
an_rec_for_type_by_day.append('N/A')
an_rec_forDF.append('')
d_forDF["Дата"] = dates
d["Дата"] = dates
d_nodate[f"{analysis_type.a_name} ({analysis_type.a_measur})"] = an_rec_for_type_by_day
d[f"{analysis_type.a_name} ({analysis_type.a_measur})"] = an_rec_for_type_by_day
d_forDF[f"{analysis_type.a_name} ({analysis_type.a_measur})"] = an_rec_forDF
except:
pass
# print('Ошибка')
only_dates = d_forDF["Дата"]
new_df = pd.DataFrame(d_forDF)
return render(request, 'journal/patient_filtered_analysis.html',
{'analysises':analysises, 'query_set':query_set, 'd_nodate':d_nodate, 'dates':only_dates, 'analysis_group':analysis_group, 'new_df':new_df.to_html(index=False), 'patient_filtered_analysis': patient_filtered_analysis, 'patient_info':patient_info, 'analysis_group_list':analysis_group_list,
'analysis_types_in_group':analysis_types_in_group})
And finally draw a ChartJs graph with html help
const data = {
labels: dateChartJs,
datasets: [
{% for key, value in d_nodate.items %}
//Если добавить еще один - будет сдвоенный график
{
label: '{{key}}',
data: [{% for i in value %}'{{i}}',{% endfor %%}],
tension: 0.4,
fill: false,
spanGaps: true,
borderWidth: 4,
datalabels: {
anchor: 'end',
align: 'top',
offset: 10,
font: {size: 14},
},
},
{% endfor %}
],};
Two main problems i got is multiple duplicating sql and similar colors for lables on each loop
Will appreciate some advice. Thank you for your attention
Related
I'm having trouble with both my serializer and models for a table using foreign keys. I have a view for my Cost table ( see below ) that when I query, I get the following output in about 300-400 ms :
[
{
"id": 12,
"hours1": 10,
"hours2": 0,
"hours3": 0,
"hours4": 0,
"date": "2021-07-12",
"employee": 14,
"job1": 417,
"job2": 671,
"job3": 671,
"job4": 671
},
{
"id": 13,
"hours1": 8,
"hours2": 0,
"hours3": 0,
"hours4": 0,
"date": "2021-07-12",
"employee": 10,
"job1": 411,
"job2": 671,
"job3": 671,
"job4": 671
}
]
The employee, job1, job2, job3, job4 fields are foreign key IDs that I wish to see their main/primary value for (in this case, names!). I've played around with a serializer to achieve this, however, the problem is that it takes about 90 seconds per query and keeps getting longer!
[
{
"id": 12,
"employee": {
"employee_name": "Person 1"
},
"job1": {
"No": "30201"
},
"job2": {
"No": "N/A"
},
"job3": {
"No": "N/A"
},
"job4": {
"No": "N/A"
},
"hours1": 10,
"hours2": 0,
"hours3": 0,
"hours4": 0,
"date": "2021-07-12"
},
{
"id": 13,
"employee": {
"employee_name": "Person 2"
},
"job1": {
"No": "30101"
},
"job2": {
"No": "N/A"
},
"job3": {
"No": "N/A"
},
"job4": {
"No": "N/A"
},
"hours1": 8,
"hours2": 0,
"hours3": 0,
"hours4": 0,
"date": "2021-07-12"
}
]
My schema and serializers:
class Employee(models.Model):
employee_name = models.CharField(max_length=200, unique=True)
employee_email = models.CharField(max_length=200)
employee_navID = models.CharField(max_length=200)
employee_department = models.CharField(max_length=200)
joining_date = models.DateField()
leaving_date = models.DateField()
weekly_salary = models.IntegerField(default=0)
car_allowance = models.IntegerField()
national_insurance = models.IntegerField()
pension = models.IntegerField()
created_at = models.DateField(auto_now_add=True)
#property
def status(self):
if(self.leaving_date >= date.today()):
return "active"
else:
return "inactive"
#property
def employee_cost(self):
return self.weekly_salary + self.car_allowance + self.national_insurance + self.pension
class Meta:
verbose_name_plural = "Employees"
def __str__(self):
return self.employee_name
class ExcelJobsList(models.Model):
No = models.CharField(max_length=200)
Description = models.CharField(max_length=200)
Custom_No = models.CharField(max_length=200)
Sell_to_Name = models.CharField(max_length=200)
Status = models.CharField(max_length=200)
Person_Responsible = models.CharField(max_length=200)
Region_Code = models.CharField(max_length=200)
Market_Code = models.CharField(max_length=200)
Agreement_Form_Code = models.CharField(max_length=200)
Technology_Code = models.CharField(max_length=200)
secondappr_Code = models.CharField(max_length=200)
Search_Description = models.CharField(max_length=200)
Work_in_Progress_Status = models.CharField(max_length=200)
Job_Category = models.CharField(max_length=200)
Project_Manager = models.CharField(max_length=200)
Sales_Person = models.CharField(max_length=200)
Payment_Terms_Code = models.CharField(max_length=200)
First_Agreement_No = models.CharField(max_length=200)
No_of_Service_Agreements = models.CharField(max_length=200)
CRM_Reference = models.CharField(max_length=200)
class Meta:
verbose_name_plural = "Jobs"
def __str__(self):
return self.No
These are populated with a unique list of employees and jobs respectively. I then use to this to create a basic timesheet form where users can assign hours to a job (up to 4). This is posted to the below model, which has foreign keys to the employee and job table.
class Cost(models.Model):
employee = models.ForeignKey(
Employee, default=1, on_delete=SET_DEFAULT)
job1 = models.ForeignKey(ExcelJobsList, default=0, on_delete=SET_DEFAULT)
hours1 = models.IntegerField()
job2 = models.ForeignKey(
ExcelJobsList, default=0, on_delete=SET_DEFAULT, related_name="job2")
hours2 = models.IntegerField()
job3 = models.ForeignKey(
ExcelJobsList, default=0, on_delete=SET_DEFAULT, related_name="job3")
hours3 = models.IntegerField()
job4 = models.ForeignKey(
ExcelJobsList, default=0, on_delete=SET_DEFAULT, related_name="job4")
hours4 = models.IntegerField()
date = models.DateField()
This produces the follow output after I've selected the fields I wanted from a serializer:
class JobModelSerializer(serializers.ModelSerializer):
class Meta:
model = ExcelJobsList
fields = ['No']
class EmployeeModelSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ['employee_name']
class CostModelSerializer(serializers.ModelSerializer):
employee = EmployeeModelSerializer()
job1 = JobModelSerializer()
job2 = JobModelSerializer()
job3 = JobModelSerializer()
job4 = JobModelSerializer()
class Meta:
model = Cost
fields = ('__all__')
class CostListFilter(filters.FilterSet):
class Meta:
model = Cost
fields = {
'employee': ['exact'],
}
class JoinedFilterCostList(generics.ListAPIView):
queryset = Cost.objects.filter()
serializer_class = CostModelSerializer
filter_backends = [DjangoFilterBackend]
filterset_class = CostListFilter
I've tried using to_field= 'xyz', however, this ends up returning null so either I'm missing something in my model or the serializer isn't set up correctly for it... or both!
Any help would be much really appreciated.
The slowness is caused by having to hit the database 4 times per Cost instance to get all the related ExcelJobsList.
To avoid this and make it more efficient, you can use select_related to the related ExcelJobsList like this:
class JoinedFilterCostList(generics.ListAPIView):
...
queryset = Cost.objects.select_related('job1', 'job2', 'job3', 'job4')
...
These should in turn end up with just one query, with inner joins on the related ExcelJobsList.
I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. multipart/form-data is used because there is an image field that needs to be sent in arrays.
But I got the following error.
Category field is required
The data is sent like this
name: Soap
category[0]: 7
category[1]: 23
brand: 7
collection: 11
availability: in_stock
warranty: no_warranty
service: cash_on_delivery
rating: 3
best_seller: true
top_rated: true
featured: true
main_product_image: (binary)
merchant: 2
variants[0][product_id]: fgfdg
variants[0][price]: 127
variants[0][quantity]: 1
variants[0][color]: red
variants[0][size]: M
variants[0][variant_availability]: not_available
variants[0][variant_image]: (binary)
variants[1][product_id]: fgfdg
variants[1][price]: 127
variants[1][quantity]: 1
variants[1][color]: red
variants[1][size]: M
variants[1][variant_availability]: not_available
variants[1][variant_image]: (binary)
The same issue is with the variants.
My models:
class Variants(models.Model):
product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True)
price = models.DecimalField(decimal_places=2, max_digits=20,default=500)
size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True)
color = models.CharField(max_length=70, default="not applicable",blank=True,null=True)
variant_image = models.ImageField(upload_to="products/images", blank=True,null=True)
thumbnail = ImageSpecField(source='variant_image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product
variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available')
class Meta:
verbose_name_plural = "Variants"
def __str__(self):
return self.product_id
#Product Model
class Product(models.Model):
merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
category = models.ManyToManyField(Category, blank=False)
sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
featured = models.BooleanField(default=False) # is product featured?
best_seller = models.BooleanField(default=False)
top_rated = models.BooleanField(default=False)
tags = TaggableManager(blank=True) # tags mechanism
name = models.CharField(max_length=150,unique=True)
main_product_image = models.ImageField(upload_to="products/images", null=True, blank=True)
thumbnail = ImageSpecField(source='main_product_image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
slug = models.SlugField(max_length=200,blank=True)
description = RichTextField(blank=True)
#picture = models.ImageField(upload_to="products/images", null=True, blank=True)
picture = models.ManyToManyField(ImageBucket,null=True,blank=True,verbose_name="Add extra 3 images")
rating = models.IntegerField(choices=((1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5))
)
availability = models.CharField(max_length=70, choices=AVAILABILITY, default='in_stock')
warranty = models.CharField(max_length=100, choices=WARRANTY, default='no_warranty')
services = models.CharField(max_length=100, choices=SERVICES, default='cash_on_delivery')
variants = models.ManyToManyField(Variants,related_name='products')
My view:
class ProductAddAPIView(CreateAPIView):
permission_classes = [IsAuthenticated]
parser_classes = [MultiPartParser,JSONParser,FormParser]
# queryset = Product.objects.all()
serializer_class = AddProductSerializer
Here I have used parser class just in case if it works.
Updated Code:
class AddProductSerializer(serializers.ModelSerializer):
id = serializers.PrimaryKeyRelatedField(read_only=True)
variants = VariantSerializer(many=True)
slug = serializers.SlugField(read_only=True)
class Meta:
model = Product
fields = ['id','merchant','featured', 'top_rated','category','brand','collection','sub_category',
'name','slug','description', 'main_product_image','best_seller','picture',
'rating','availability','warranty','services','variants']
#depth = 1
def create(self, validated_data):
#user = self.context['request'].user
picture_data = validated_data.get('picture')
merchant = validated_data.get('merchant')
category_data = validated_data.get('category')
featured = validated_data.get('featured')
top_rated = validated_data.get('top_rated')
brand = validated_data.get('brand')
collection = validated_data.get('collection')
sub_category = validated_data.get('sub_category')
name = validated_data.get('name')
description = validated_data.get('description')
main_product_image = validated_data.get('main_product_image')
best_seller = validated_data.get('best_seller')
rating = validated_data.get('rating')
availability = validated_data.get('availability')
warranty = validated_data.get('warranty')
services = validated_data.get('services')
#variants_logic
variants_data = validated_data.get('variants')
#breakpoint()
print(variants_data)
# from pudb import set_trace;set_trace()
#products-logic
product = Product.objects.create(featured=featured,top_rated=top_rated,
brand=brand,collection=collection,sub_category=sub_category,
name=name,description=description,
main_product_image=main_product_image,
best_seller=best_seller,rating=rating,
availability=availability,warranty=warranty,
services=services,merchant=merchant)
product.save()
product.category.set(category_data)
# product.variants.set(variants_data)
product.save()
for variants_data in variants_data:
abc = Variants.objects.create(**variants_data)
product.variants.add(abc)
product.save()
return product
im new in django, and im doing an ecommerce website. I have a problem, When I click on a subcategory its okay, it shows all the products of that subcategory. But I want to click on a category parent and show all the products that his children has, and i dont know how to do that.
Here is my models:
class Category(models.Model):
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null = True)
title = models.CharField(max_length= 200, null = True)
slug = models.SlugField(max_length=200, null = True)
ordering = models.IntegerField(default = 0)
class Meta:
verbose_name_plural = 'Categories'
ordering = ('ordering',)
def __str__(self):
return self.title
class Product(models.Model):
name = models.CharField(max_length = 255, null = True)
slug = models.SlugField(max_length=200)
category = models.ForeignKey(Category, related_name='products', on_delete = models.CASCADE)
parent = models.ForeignKey('self', related_name = 'variants', on_delete = models.CASCADE, blank = True, null = True)
brand = models.ForeignKey(Brand, related_name='products', null = True, on_delete = models.CASCADE)
description = models.TextField(blank = True, null = True)
price = models.FloatField(null = True)
disccount = models.BooleanField(default = False)
disccount_price = models.FloatField(blank = True, null = True)
image = models.ImageField(upload_to = 'images/',blank = True, null = True)
thumbnail = models.ImageField(upload_to = 'images/', blank = True, null = True)
date_added = models.DateTimeField(auto_now_add = True)
class Meta:
ordering = ('-date_added',)
def __str__(self):
return self.name
Here is my view:
def category_detail(request, slug):
products = Product.objects.all()
subcategories = []
if slug:
category = get_object_or_404(Category, slug=slug)
products = products.filter(category = category)
subcategories = Category.objects.filter(parent = category)
context = {
'category': category,
'subcategories': subcategories,
'products' : products,
}
return render(request, 'category_detail.html', context)
So please I need some help:(
You can filter on Products that belong to a subcategory of a category category with:
products = products.filter(category__parent=category)
or if you want Products that belong to the category or to a category with as parent the category, you can filter with Q objects [Django-doc]:
from django.db.models import Q
products = products.filter(
Q(category__parent=category) |
Q(category=category)
)
Django is giving me this error. The solution I've tried does not seem to work. It is asking me to make this an instance of Medication...Am I not already doing that? I'm trying to have two serializers cat and medication under the one careLogSerializer. Is that even possible? How can I best solve this error?
builtins.ValueError
ValueError: Cannot assign "OrderedDict([('name', 'carelog3'), ('duration', 'short'), ('frequency', '4')])": "CareLog.medication" must be a "Medication" instance.
Here is my serializer....
class CareLogSerializer(serializers.HyperlinkedModelSerializer):
cat = CatSerializer()
medication = MedicationSerializer()
# cat = CatSerializer(read_only=True) this allows put BUT TURNS OFF POST
class Meta:
model = CareLog
fields = (
'cat',
'slug',
'foster_manager',
'weight_unit_measure',
'weight_before_food',
'food_unit_measure',
'amount_of_food_taken',
'food_type',
'weight_after_food',
'stimulated',
'medication',
'medication_dosage_given',
'medication_dosage_unit',
'notes',
'created',
'photo',
)
extra_kwargs = {
'foster_manager': {
'read_only': True,
'required': False,
'lookup_field': 'id',
},
'medication': {
'read_only': True,
'required': False,
'lookup_field': 'slug',
},
'cat': {
'read_only': True,
'required': False,
'lookup_field': 'slug',
},
}
#staticmethod
def create(validated_data):
cat_data = validated_data.pop('cat')
cat_obj = Cat.objects.get(**cat_data)
return CareLog.objects.create(cat=cat_obj, **validated_data)
#staticmethod
def update(instance, validated_data):
instance.weight_unit_measure = validated_data['weight_unit_measure']
instance.weight_before_food = validated_data['weight_before_food']
instance.food_unit_measure = validated_data['food_unit_measure']
instance.amount_of_food_taken = validated_data['amount_of_food_taken']
instance.food_type = validated_data['food_type']
instance.weight_after_food = validated_data['weight_after_food']
instance.stimulated = validated_data['stimulated']
instance.stimulation_type = validated_data['stimulation_type']
instance.notes = validated_data['notes']
instance.save()
Here is my model
class CareLog(models.Model):
WEIGHT_MEASURE_CHOICES = (
('OZ', '(oz) Ounces'),
('LB', '(lb) Pounds'),
('G', '(G) Grams')
)
OUNCES = 'OZ'
POUNDS = 'LB'
GRAMS = 'G'
VOLUME_MEASURE_CHOICES = (
('ML', '(ml) Milliliters'),
('CC', '(cc) Cubic Centimeters'),
('OZ', '(oz) Ounces'),
('G', '(G) Grams')
)
MILLILITERS = 'ML'
CUBIC_CENTIMETERS = 'CC'
FOOD_TYPE_CHOICES = (
('MN', 'Mom (Nursing)'),
('BO', 'Bottle'),
('BS', 'Bottle / Syringe'),
('SG', 'Syringe Gruel'),
('GG', 'Syringe Gruel / Gruel'),
('G', 'Gruel')
)
BOTTLE = 'BO'
BOTTLE_SYRINGE = 'BS'
SYRINGE_GRUEL = 'SG'
SYRINGE_GRUEL_GRUEL = 'GG'
GRUEL = 'G'
STIMULATION_CHOICES = (
('UR', 'Urine'),
('FE', 'Feces'),
('UF', 'Urine / Feces'),
)
URINE = 'UR'
FECES = 'FE'
URINE_FECES = 'UF'
cat = models.ForeignKey(Cat)
slug = AutoSlugField(max_length=255, unique=True, blank=True, null=True)
foster_manager = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
weight_unit_measure = models.CharField(max_length=2, choices=WEIGHT_MEASURE_CHOICES, default=GRAMS)
weight_before_food = models.IntegerField(blank=True, null=True)
food_unit_measure = models.CharField(max_length=2, choices=WEIGHT_MEASURE_CHOICES, default=GRAMS)
amount_of_food_taken = models.IntegerField(blank=True, null=True)
food_type = models.CharField(max_length=2, choices=FOOD_TYPE_CHOICES, blank=True, null=True)
weight_after_food = models.IntegerField(blank=True, null=True)
stimulated = models.BooleanField(default=False)
stimulation_type = models.CharField(max_length=2, choices=STIMULATION_CHOICES, blank=True, null=True)
medication = models.ForeignKey(Medication, blank=True, null=True)
medication_dosage_given = models.FloatField(blank=True, null=True)
medication_dosage_unit = models.CharField(max_length=2, choices=VOLUME_MEASURE_CHOICES, blank=True, null=True,
help_text="If left blank this will default to "
"the default unit for the medication.")
notes = models.TextField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
photo = models.FileField(upload_to="kitty_photos", blank=True, null=True)
def save(self, *args, **kwargs):
# Update Cat's weight if 'Weight After Food' is updated
if self.weight_after_food:
self.cat.weight = self.weight_after_food
self.cat.save()
# Get all previous cat feedings
feedings = CareLog.objects.filter(cat=self.cat).order_by('-id')
if feedings:
# if the list of cat feedings contains the current, get rid of current from the list
if feedings[0] == self:
feedings = feedings[1:]
# TODO You broke it you fix it:
# If the feeding is a weight loss log it as the first/second/third
if self.weight_after_food < feedings[0].weight_after_food:
if self.cat.first_weight_loss:
self.cat.second_weight_loss = True
elif self.cat.second_weight_loss:
self.cat.third_weight_loss = True
elif self.cat.third_weight_loss:
self.cat.many_weight_losses = True
elif not self.cat.first_weight_loss:
self.cat.first_weight_loss = True
# Save Cat Object
self.cat.save()
if self.medication and not self.medication_dosage_unit:
self.medication_dosage_unit = self.medication.dosage_unit
super(CareLog, self).save(*args, **kwargs)
def __str__(self):
return "{cat}: {timestamp}".format(cat=self.cat.name, timestamp=self.created)
In your create method you need to do for medication same operation as for cat. Create object first and assign it to CareLog:
#staticmethod
def create(validated_data):
cat_data = validated_data.pop('cat')
cat_obj = Cat.objects.get(**cat_data)
med_data = validated_data.pop('medication')
med_obj = Medication.objects.create(**med_data)
return CareLog.objects.create(cat=cat_obj, medication=med_obj, **validated_data)
Otherwise Django trying to set as foreignkey's value dict object and raise the error.
Hey i have looked around through some simliar posts here on SO but havent found anything that has solved my problem. I have the following models,
from django.db import models
class Areas(models.Model):
name = models.CharField(max_length = 120)
order_in_sidebar_network = models.IntegerField(blank=True, null=True)
order_in_section_network = models.IntegerField(blank=True, null=True)
def __unicode__ (self):
return self.area_name
class Meta:
verbose_name_plural = "Areas"
verbose_name = "Area"
class Countries(models.Model):
name = models.CharField(max_length = 120, help_text = "The name of the country")
area = models.ForeignKey(Areas, verbose_name = 'Area')
def __unicode__ (self):
return self.name
class Meta:
verbose_name_plural = "Countries"
verbose_name = "Country"
ordering = ['name']
class Offices(models.Model):
country = models.ForeignKey(Countries, verbose_name = 'Country')
name = models.CharField(max_length = 255, help_text = "The name of this office, IE London")
main_office = models.BooleanField(default= False, help_text = "Is this office a key location?", verbose_name = "Key Location")
address_1 = models.CharField(max_length = 255, null = True, blank = True)
address_2 = models.CharField(max_length = 255, null = True, blank = True)
address_3 = models.CharField(max_length = 255, null = True, blank = True)
city = models.CharField(max_length = 255, null = True, blank = True)
postcode = models.CharField(max_length = 20)
tel = models.CharField(max_length = 30, null= True, blank = True, help_text = "Optional telephone contact number")
mobile = models.CharField(max_length = 30, null= True, blank = True, help_text = "Optional mobile contact number")
fax = models.CharField(max_length = 30, null= True, blank = True, help_text = "Optional fax contact number")
data_1 = models.CharField(max_length = 255, null = True, blank = True, help_text = "Optional additional data", verbose_name = "Additional information")
data_2 = models.CharField(max_length = 255, null = True, blank = True, help_text = "Optional additional data", verbose_name = "Additional information")
class Meta:
verbose_name_plural = "Offices"
verbose_name = "Office"
ordering = ['name']
def __unicode__(self):
return self.name
class OfficeMembers(models.Model):
name = models.CharField(max_length = 60, help_text = "Please tell us this person name")
title = models.CharField(max_length = 100, help_text = "The person's title, IE Managing Director")
email = models.EmailField(max_length = 255, null = True, blank = True, help_text = "Optional email address for this person")
email2 = models.EmailField(max_length = 255, null = True, blank = True, help_text = "Optional second email address for this person")
phone = models.CharField(max_length = 30, null = True, blank = True, help_text = "Optional contact number for this person")
mobile = models.CharField(max_length = 30, null = True, blank = True, help_text = "Optional mobile contact number for this person")
office = models.ForeignKey(Offices, null = True)
class Meta:
verbose_name_plural = "Office Memebers"
verbose_name = "Office memebr"
ordering = ['name']
def __unicode__(self):
return self.name
i have the following view set up
def index(request):
cache_key = "world_areas"
cache_time = 60
world_areas_cache = cache.get(cache_key)
#if no cache is set, grab the objects, and set the cache
logger.debug(world_areas)
if not world_areas_cache:
logger.info('No cache found grabbing objects')
world_areas = Areas.objects.select_related().all()
#cache.set(cache_key, world_areas, cache_time)
logger.debug(world_areas)
else:
logger.info("Getting from cache")
world_areas = world_areas_cache
return render_to_response('network/index.html', {'world_areas':world_areas}, context_instance=RequestContext(request))
trying to iterate over the world_areas object like so
{% for area in world_areas %}
produces a template syntax error
'RelatedManager' object is not iterable
Any one got any ideas why this is happeing? really cant seem to get round this! strangley this is working for me in shell :S am i missing something obvious???
Big thanks to anyone able to help!
Call all() to retrieve the elements from the manager.
{% for area in world_areas.all %}
In general, it is better practice to use a values or values_list to pass data from a queryset to a template.
world_areas = Areas.objects.select_related().all().values_list('name', 'order_in_sidebar_network', ...)
Check out the Django docs for info on how to use the values function if you haven't used it before.
I run into this issue by a reckless mistake:
for physicalserver in task.physicalservers:
physicalserver.relieve_task()
The task.physicalservers is RelatedManager object, in my case I should get the task's physicalservers, there should add .all().
for physicalserver in task.physicalservers.all():
You have to iterate over set to get values related to a fk in a model.
class Area(models.Model):
name = models.CharField(max_length = 120)
order_in_sidebar_network = models.IntegerField(blank=True, null=True)
order_in_section_network = models.IntegerField(blank=True, null=True)
class CountryArea(models.Model):
name = models.CharField(max_length = 120)
area = models.ForeignKey(Area, verbose_name = 'Area')
## Assuming you have an object; area
## To get the all the counties related to that area you can do;
{% for obj in area.countryarea_set.all %}
<h4> {{ obj.name }} </h4>
{% endfor %}