Here's what I'm trying to do :
The user creates an Event in my application. Here's the model :
class Event(models.Model):
name = models.CharField(max_length=40)
organizer = models.ForeignKey(UserProfile)
description = models.TextField(null=True)
place = models.TextField(null=True)
confirmed = models.BigIntegerField(null=True)
organizer_part = models.BooleanField(default=True)
slug = models.SlugField()
Right after that, it posts the different people invited to this event, and the different dates that the user chose. Here are the models :
class EventDate(models.Model):
"""Correspondances date-event"""
event = models.ForeignKey(Event)
date = models.BigIntegerField()
class EventPeople(models.Model):
"""Correspondances personne-event"""
event = models.ForeignKey(Event)
phone_number = models.PositiveIntegerField()
name = models.CharField(max_length=32)
answer = models.BooleanField()
participation = models.NullBooleanField()
I'd like to fill those three models in only one request. So far I have to make three requests. I can't see how I could possibly do it.
Any idea would be highly appreciated.
Resource that should work with your models is:
class EventResource(ModelResource):
event_dates = fields.ToManyField(EventDateResource, 'event_dates')
event_peoples = field.ToManyField(EventPeopleResource, 'event_peoples')
class Meta:
queryset = Event.objects.all()
Also you have to create simple EventDateResource and EventPeopleResource.
One one more change in yout models, you need to add related_names:
class EventDate(models.Model):
"""Correspondances date-event"""
event = models.ForeignKey(Event, related_name='event_dates')
date = models.BigIntegerField()
class EventPeople(models.Model):
"""Correspondances personne-event"""
event = models.ForeignKey(Event, related_name='event_peoples')
phone_number = models.PositiveIntegerField()
name = models.CharField(max_length=32)
answer = models.BooleanField()
participation = models.NullBooleanField()
Related
I've been searching Google, but couldn't find a simple answer to this problem:
I have a django models that stores students information and three other models like this:
class Level(models.Model):
name = models.CharField(max_length=50)
class Pricing(models.Model):
level = models.ForeignKey(Level, on_delete=models.PROTECT)
price = models.PositiveSmallIntegerField(default=0)
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.PROTECT)
level = models.ForeignKey(Level, on_delete=models.CASCADE)
date_enrolled = models.DateField()
price = models.PositiveSmallIntegerField(default=0)
I want the Enrollment.price field to be populated dynamically depending on Enrollment.level field value. In javascript, it amounts to setting an event listener to Enrollement.level, but I can't find the equivalent in django.
hi you can modify your save method to fill automatically field price from Level model
Enrollment.level
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.PROTECT)
level = models.ForeignKey(Level, on_delete=models.CASCADE)
date_enrolled = models.DateField()
price = models.PositiveSmallIntegerField()
def save(self,*args,**kwargs):
self.price = Pricing.objects.get(level=self.level).price
super().save(*args,*kwargs)
but I recommend to rewrite your model like above example because its simple and you can access to price of every level directly
like Enrollment.level.price
class Level(models.Model):
level = models.CharField(max_length=50,unique=True)
price = models.PositiveSmallIntegerField(default=0)
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.PROTECT)
level = models.ForeignKey(Level, on_delete=models.CASCADE)
date_enrolled = models.DateField()
I hope it helped you
I'm new in Django and DRF, have questions with serialization.
I have models:
class Commodity(models.Model):
shop = models.ForeignKey(Company, on_delete=models.PROTECT)
price = models.DecimalField(max_digits=10, decimal_places=2)
active = models.BooleanField(default=False)
class Clother(models.Model):
commodity = models.ForeignKey(Commodity, related_name='commodity', on_delete=models.CASCADE)
color = models.ManyToManyField(Color, related_name='color')
material = models.ManyToManyField(Material, related_name='material')
gender = models.CharField(max_length=2, choices=GENDER_CHOICES, default=UNISEX)
class Outwear(models.Model):
clother = models.ForeignKey(Clother, on_delete=models.CASCADE)
name = models.CharField(max_length=30, blank=True)
outwear_type = models.ForeignKey(OutwearType, on_delete=models.CASCADE)
size = models.ManyToManyField(ClotherSize)
So I suppose to make a Serializer like that:
class OutwearSerializer(serializers.ModelSerializer):
commodity = CommoditySerializer(many=False, read_only=False)
clother = ClotherSerializer(many=False, read_only=False)
class Meta:
model = Outwear
fields = ('commodity', 'clother', 'name', 'outwear_type', 'size')
As I understand that read_only fields let me add or edit Outwear object further, but I supposed to have 2 types of permition:
All users can see only active Commodity objects.
Only Companies can create and edit their own objects.
Do I need to make 2 Serializer Models for read_only=True/False?
What is the best practice and where can I find good examples of something familiar?
I call User - unauthorized User. Company is authorized User.
Thanks!
For your first question:
class CommoditySerializer(ModelSerializer):
class Meta:
model = Commodity
fields = (shop, price)
Class CommodityActiveAPIView(generics.ListAPIView):
serializer_class = serializers.CommoditySerializer
queryset = Commodity.objects.filter(active=True)
second question is ambiguous. first define user role please
I have a three simple models:
class Task(models.Model):
code = models.CharField(max_length=200, unique=True)
tags = models.ManyToManyField(Tag, blank=True)
class Session(models.Model):
tasks = models.ManyToManyField(Task, through='TaskInSession')
and
class TaskInSession(models.Model):
session = models.ForeignKey(Session, on_delete=models.CASCADE)
task = models.ForeignKey(Task, on_delete=models.CASCADE)
count = models.IntegerField()
For session editing I have:
class SessionAdmin(admin.ModelAdmin):
inlines = [TaskInSessionInline,]
exclude = ('tasks', )
Is it possible to add tasks filterting by tag possibility, for easy task selection on session editing?
you should have in models.py your Tag class defined. Maybe something like this:
class Tag(models.Model):
Name = models.CharField(max_length=200, unique=True)
Then in your views.py you get the desired Tag. For instance:
desired_tag = Tag.objects.get(Name='some_name') # you could as well get the desired tagby the pk attribute.
Finally, Get all the tasks associated with that Tag. Example:
filtered_tasks = Tasks.objects.filter(tags=desired_tag)
The query you are looking would be filtered_tasks.
curr = curr = get_object_or_None('Page', menu__slug=slug1, menu__parent__slug=slug2).prefetch_related('menu')
Need to use prefetch_related to get info from ForeignKey like an object and get None if it is not in table. Who knows, can I realize it by using get_object_or_None? It seems to work, but read, that it will not. Why so?
class Menu(models.Model):
name = models.CharField()
parent = models.ForeignKey('self', related_name='children')
slug = models.SlugField()
region = models.ForeignKey()
pos = models.IntegerField()
on_top = models.BooleanField()
nofollow = models.BooleanField()
class Page(models.Model):
title = models.CharField()
name = models.CharField()
menu = models.ForeignKey('Menu')
meta_key = models.TextField()
meta_desc = models.TextField()
body = models.TextField()
has_certificate = models.BooleanField()
get_object_or_None() is meant to be a shortcut to specifying a try except block, and it doesn't return a QuerySet, the class where prefetch_related() is from.
Also, if you're trying to get just one instance of your model you're not getting any performance enhancement by prefetching, in fact you'll make your query heavier on the db.
I'm stuggling to get to grips with relationships in ORM.
I want to get a distinct CostItem queryset related to a particular event.
Normally I'd filter CostFixedList for the particular event I'm interested and get a the Cost_Rate id's. From that I could then get the CostItem id's.
I could do this easily in SQL, but can't understand how to start with ORM. Can anyone point me in the right direction?
class Event(models.Model):
event_type = models.ForeignKey(EventType)
retailer = models.ForeignKey(Retailer)
....
class CostItem(models.Model):
name = models.CharField("Name", max_length=50, unique=True)
cost_type = models.ForeignKey(CostType, verbose_name="Type")
active = models.BooleanField("Active", default=True)
class CostRate(models.Model):
cost_item = models.ForeignKey(CostItem, verbose_name="Item")
valid_from = models.DateField("From")
valid_till = models.DateField("Till")
unit_amount = models.DecimalField("Price Per Unit", max_digits=5, decimal_places=2)
class CostFixedList(models.Model):
event = models.ForeignKey(Event)
cost_rate = models.ForeignKey(CostRate)
units = models.IntegerField()
appointment = models.ForeignKey(Appointment, null=True, blank=True)
I think this should do it (where myevent is the event for which you wish to obtain the CostItem queryset):
qs = CostItem.objects.filter(costrate__costfixedlist__event=myevent)