Problem:
I am in need to store 2D array in one of the field of the Table.
Example
id:1
Teacher_name:"Amit"
time: [[9:00am, 2:00pm], [2:00pm,6:00pm], [6:00am, 9:00pm]] # Need to store 2-D array kind of multiple time stamps in a field,
code is here:
Model.py
class ScheduleClassification(models.Model):
vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True)
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=1000)
start_date = models.DateField(auto_now_add=True)
end_date = models.DateField(auto_now_add=True)
duration = models.CharField(max_length=20, default="forever")
day_type = models.CharField(max_length=20)
time = #how do i make this field
how can i store this please let me know the best way to do this. in django models
First it isn't a good way to store the whole array what you must do is
Create New Model That will have the start and end time of Lesson for Teacher and the Schedule
class Lesson(models.Model):
start = models.DateTimeField()
end = models.DateTimeField()
duration = models.CharField(max_length=20, default="forever")
teacher = models.ForeignField(Teacher)
schedule = models.ForeignField(Schedule)
this is a better way and you can create a function that will make the array you want
# in the Schedule Class
def create_array(self):
array = []
qs = Lesson.objects.filter(schedule=self)
for lesson in qs.iterator():
lesson = [ lesson.start , lesson.end]
array.append(lesson)
return array
also you can make this function property to enhance it
Related
I am trying to adapt the Viewflow Dynamicsplit example
The objective is to split approvals of an Order based on OrderLines and to assign them to the appropriate approver. It seems that this should be possible as there seems to be a possibility described in this answer - Assign user to tasks automatically (Viewflow, Django)
The issue is that whenever I try to grab the current order pk in the DynamicSplitActivation - the queryset comes back empty. Not sure where I am going wrong. The queryset works fine if I set the pk manually, but as soon as I try to use a dynamic variable it stops working.
I have listed the flow and models etc. at the end of the post, however, I am guessing the issue is quite basic. Any help would be appreciated!
nodes.py
...
class DynamicSplitActivation(AbstractGateActivation):
def calculate_next(self):
self._order = self.flow_task._order_callback(self.process)
order_id = self._order.pk
# order_id = 28
order_lines = models.OrderLine.objects.filter(order_id=order_id)
project_lines = project_models.ProjectLine.objects.filter(orderline__in=order_lines)
users = User.objects.filter(projectline__in=project_lines).distinct()
self._approvers = users
...
class DynamicSplit(...):
...
def __init__(self, callback):
super(DynamicSplit, self).__init__()
self._order_callback = callback
self._ifnone_next_node = None
...
flows.py
...
approval_split = (
nodes.DynamicSplit(lambda act: act.order)
.IfNone(this.end)
.Next(this.split_approval_budget)
)
models.py
...
class ProjectLine(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
description = models.CharField(max_length=50)
budget_holder = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
class Order(models.Model):
description = models.CharField(max_length=30)
class OrderLine(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
project_line = models.ForeignKey(project_models.ProjectLine, on_delete=models.SET_NULL, null=True, blank=False)
product = models.ForeignKey(catalogue_models.Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
budgetholder_approved = models.BooleanField(null=True)
class OrderProccess(Process):
order = models.ForeignKey(Order, blank=True, null=True, on_delete=models.CASCADE)
...
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've got a Stock table and a StockArchive table.
My Stock table consists of roughly that 10000 stocks that I update daily. The reason I have a StockArchive table is because I still wanna some historic data and not just update existing records. My question is, is this a proper way of doing it?
First, my models:
class Stock(models.Model):
objects = BulkUpdateOrCreateQuerySet.as_manager()
stock = models.CharField(max_length=200)
ticker = models.CharField(max_length=200)
exchange = models.ForeignKey(Exchange, on_delete=models.DO_NOTHING)
eod_price = models.DecimalField(max_digits=12, decimal_places=4)
currency = models.CharField(max_length=20, blank=True, null=True)
last_modified = models.DateTimeField(blank=True, null=True)
class Meta:
db_table = "stock"
class StockArchive(models.Model):
objects = BulkUpdateOrCreateQuerySet.as_manager()
stock = models.ForeignKey(Stock, on_delete=models.DO_NOTHING)
eod_price = models.DecimalField(max_digits=12, decimal_places=4)
archive_date = models.DateField()
class Meta:
db_table = "stock_archive"
I proceed on doing the following:
#transaction.atomic
def my_func():
archive_stocks = []
batch_size = 100
old_stocks = Stock.objects.all()
for stock in old_stocks:
archive_stocks.append(
StockArchive(
stock=stock.stock,
eod_price = stock.eod_price,
archive_date = date.today(),
)
)
# insert into stock archive table
StockArchive.objects.bulk_create(archive_stocks, batch_size)
# delete stock table
Stock.objects.all().delete()
# proceed to bulk_insert new stocks
I also wrapped the function with a #transaction.atomic to make sure that everything is committed and not just one of the transactions.
Is my thought process correct, or should I do something differently? Perhaps more efficient?
I have following two models.
class TeacherInfo(models.Model):
name = models.CharField(max_length=200)
school_id = models.ForeignKey('admin_app.School')
timestamp = models.DateTimeField(auto_now=True, blank=True)
class AssignedSheetStatus(models.Model):
level = models.ForeignKey('admin_app.Levels')
subject = models.ForeignKey('admin_app.Subject')
set = models.ForeignKey('admin_app.Set')
teacher = models.ForeignKey('teacher.TeacherInfo')
assigned_count = models.PositiveIntegerField(default=0)
corrected_count = models.PositiveIntegerField(default=0)
timestamp = models.DateTimeField(auto_now_add=True)
Now I want to join these two tables such that I have name from TeacherInfo and sum of assigned_count , corrected_count.
Normally for one teacher I would do :
AssignedSheetStatus.objects.filter(teacher__id=teacher_id).aggregate(Sum('assigned_count'), Sum('corrected_count'))
But here I want this for all of the teachers in TeacherInfo.
What is the best way to achieve this?
You can do it the other way arround. Annotate over the TeacherInfo:
TeachInfo.objects.annotate(Sum('assignedshetsstatus__assigned_count'), Sum('assignedsheetstatus__corrected_count'))
I want to find the number of articles for which a specific user has created articlehistory records.
The models for that look like this:
class Article(models.Model):
"""The basic entity of this app.)"""
documentID = models.CharField(blank=True, max_length=1000)
cowcode = models.IntegerField(blank=True, null=True)
pubdate = models.DateField(default=datetime.datetime.today)
headline = models.CharField(blank=True, max_length=1500)
source = models.CharField(blank=True, max_length=5000)
text = models.TextField(blank=True, max_length=1000000)
assignments = models.ManyToManyField(Assignment)
class Meta:
ordering = ['pubdate']
def __unicode__(self):
return self.headline
class ArticleHistory(models.Model):
"""(Modelname description)"""
article = models.ForeignKey(Article, related_name='Article History')
coder = models.ForeignKey(User, related_name='Article History')
last_updated = models.DateTimeField(default=datetime.datetime.now)
def __unicode__(self):
return self.last_updated
The way I'm trying to do this at the moment is like this:
assignment.finished_articles = Article.objects.filter(cowcode=country).filter(pubdate__range=(start_date,end_date), articlehistory__coder=request.user.id).count()
This doesn't work, however and exhibits another weird behaviour:
I try to do this:
for assignment in assignments:
country = assignment.country.cowcode
start_date = assignment.start_date
end_date = assignment.end_date
articles = Article.objects.filter(cowcode=country).filter(pubdate__range=(start_date,end_date)).select_related()
assignment.article_num = articles.count()
#assignment.finished_articles = Article.objects.filter(cowcode=country).filter(pubdate__range=(start_date,end_date), articlehistory__coder=request.user.id).count()
This works fine, unless I try to include finished_articles, then article_num gets shortened to one result.
It would be really great if anyone has a pointer to who to solve this.
Make use of reverse relation of ForeignKey created by parameter related_name:
Rename attribute related name to "article_history_set".
Now, it gives you easy pointer: user.article_history_set is a set of Article History objects where coder is set to this user.
Then you can find which article it is related to by doing article_history.article.
At the end, you have to get rid of repetition and get length of that list.
Here you have more about related_name attribute: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name