Copy or clone an object instance in Django/Python - python

I've following scenario:
class CourseTemplate(models.Model):
title = models.CharField(max_length=70)
teacher = models.ForeignKey(User)
description = models.TextField()
max_students = models.IntegerField()
sessions = models.ManyToManyField(CourseSession) # e.g. Session 1 Introduction, Session 2 Basics, etc.
rating = models.ManyToManyFields(StudentRating)
date_added = models.DateTimeField()
class CourseEnrollment(models.Model):
course = models.OneToOneField(CourseTemplate) # Each enrollment needs a new CourseTemplate Instance, so I can track it
students = models.ManyToManyField(User)
Class CourseSession(models.Model):
title = models.CharField(max_length=50)
date = models.DateTimeField()
details = models.CharField(max_length=100)
address = models.TextField()
#parent_course = models.ForeignKey(CourseTemplate)
class StudentRating(models.Model):
student = models.ForeignKey(User)
rating = models.IntegerField()
#course = models.ForeignKey(CourseTemplate)
Now a teacher (=User) can create a CourseTemplate with all the required details first. After it's saved, he can create a concrete "enrollment" for e.g. this semester with 5 sessions. Maybe he changes after 8 enrollments some details (e.g. CourseTemplate.description or the course now only has 7 sessions instead of 8).
I'd like to have a 1:1 relationship between each CourseTemplate instance and each CourseEnrollment, so I can see for example:
- Teacher X had 2012 three CourseEnrollments, two of them were the same or
- which rating has he received for his second course.
The presented "Template" should always be the "newest", so I'd just need to get the latest instance by CourseTemplate.date_added.
Does anyone know how I can avoid this problem?
Thanks a lot!

You can duplicate any existing django model instance by clearing its primary key, and then saving it again.
ct = CourseTemplate.objects.all()[0]
print ct.pk
# some original pk
ct.pk = None
ct.save()
print ct.pk
# will be a new auto-incremented

Related

Django - SubQuery e function F()

I have 2 models (author and book). I want to annotate in the author model the highest book price for every authors (in order to manipulate it later). I would like to make a query with an internal sub-query using the F() function but the problem is that the F() is refered to the book model but I would like to refer it to the author model. I'll show that with an example. The models are shown below:
class author:
authorID = models.AutoField(primary_key = True, auto_created = True, unique = True)
name = models.CharField(max_length=100)
surname = models.CharField(max_length=100)
class book:
ownerID = models.ForeignKey(author, on_delete = models.CASCADE, related_name='hook')
title = models.CharField(max_length=100)
price = models.IntegerField()
The query in question is as follows:
value = author.objects.annotate(maxPrice = (book.objects.filter(ownerID = F('authorID')).order_by('-price') [0]))
F('authorID') is refered to the book DB and so Django returns an error but I want to refer it to the author DB to achieve my goal. How can I do that? Thanks

Not sure I understand dependancy between 2 django models

I am struggling to understand django models relationship.
I have this arborescence:
A train have cars, and those cars are divided into parts. Then those parts all contains different references.
Like, for exemple, all the trains have the 6 cars, and the cars 6 parts. Each part have x reference to be associated.
I would like to use all of them in a template later on, where the user can select the train, the car and the part he worked on, then generate a table from his selections with only the references associated to the parts he selected.
It should update the train and the car (I'm trying to update a stock of elements for a company)
I dont really understand which model field give to each of them. After checking the doc, Ive done something like this but i am not convinced:
class Train(Car):
train = models.CharField(max_length=200)
id = models.CharField(primary_key='True', max_length=100)
selected = models.BooleanField()
class Meta:
abstract = True
class Car(Part):
car = models.CharField(max_length=200)
id = models.CharField(primary_key='True', max_length=100)
selected = models.BooleanField()
class Meta:
abstract = True
class Part(Reference):
part = models.CharField(max_length=200)
id = models.CharField(primary_key='True', max_length=100)
selected = models.BooleanField()
class Meta:
abstract = True
class Reference(models.Model):
reference = models.CharField(max_length=200)
id = models.CharField(primary_key='True', max_length=100)
selected = models.BooleanField()
def __str__(self):
return self.reference
Can someone please help me understand this so I can do well ? Thanks!!
1-)if you add abstract = True in your Model Meta class, your class doesn't created on database as a table. If you store data for any class, you mustn't define abstract = True.
2-)For relations, you can use models.ForeignKey . If you add a class into brackets of another class, it names: inheritance.(You can think like parent-child relation). In database management, we can use foreignkey for one-to-many relationship.
3-)In Django ORM, id field automatically generated. So you don't need to define id field.
If I understand correctly, also you want to store parts of user's selected.
So, your model can be like that:
class Train(models.Model):
name = models.CharField(max_length=200) # I think you want to save name of train
class Car(models.Model):
train = models.ForeignKey(Train,on_delete=models.Cascade)
name = models.CharField(max_length=200)
class Part(models.Model):
car = models.ForeignKey(Car,on_delete=models.Cascade)
name = models.CharField(max_length=200)
class Reference(models.Model):
part = models.ForeignKey(Part,on_delete=models.Cascade)
name = models.CharField(max_length=200)
def __str__(self):
return self.reference
#addtional table for storing user's references
class UserReference(models.Model):
user = models.ForeignKey(User,on_delete=models.Cascade)
reference = models.ForeignKey(Reference,on_delete=models.Cascade)
name = models.CharField(max_length=200)
With this definitions, you can store user's definition on UserReference table. And with Django Orm, you can access train object from UserReferenceObject.
#user_reference: UserReference object like that result of UserReference.objects.first()
user_reference.reference.part.car.train.name

Reference multiple foreign keys in Django Model

I'm making a program that helps log missions in a game. In each of these missions I would like to be able to select a number of astronauts that will go along with it out of the astronauts table. This is fine when I only need one, but how could I approach multiple foreign keys in a field?
I currently use a 'binary' string that specifies which astronauts are to be associated with the mission (1 refers to Jeb, but not Bill, Bob, or Val and 0001 means only Val), with the first digit specifying the astronaut with id 1 and so forth. This works, but it feels quite clunky.
Here's the model.py for the two tables in question.
class astronauts(models.Model):
name = models.CharField(max_length=200)
adddate = models.IntegerField(default=0)
experience = models.IntegerField(default=0)
career = models.CharField(max_length=9, blank=True, null=True)
alive = models.BooleanField(default=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Kerbals"
class missions(models.Model):
# mission details
programid = models.ForeignKey(programs, on_delete=models.SET("Unknown"))
missionid = models.IntegerField(default=0)
status = models.ForeignKey(
missionstatuses, on_delete=models.SET("Unknown"))
plan = models.CharField(max_length=1000)
# launch
launchdate = models.IntegerField(default=0)
crewmembers = models.IntegerField(default=0)
# recovery
summary = models.CharField(max_length=1000, blank=True)
recdate = models.IntegerField(default=0)
def __str__(self):
return str(self.programid) + '-' + str(self.missionid)
class Meta:
verbose_name_plural = "Missions"
I saw a post about an 'intermediate linking table' to store the crew list but that also isn't ideal.
Thanks!
This is the use case for Django's ManyToManyField. Change the appropriate field on the missions:
class missions(models.Model):
crewmembers = models.ManyToManyField('astronauts')
You can access this from the Astronaut model side like so:
jeb = astronaut.objects.get(name='Jebediah Kerman')
crewed_missions = jeb.missions_set.all()
Or from the mission side like so:
mission = missions.objects.order_by('?')[0]
crew = mission.crewmembers.all()
This creates another table in the database, in case that is somehow a problem for you.

How use a few foreignkey in view.py django and make some logic?

I have some models
class Apartment(models.Model):
name = models.CharField(max_length=50)
floor = models.IntegerField()
square = models.FloatField()
conditioner = models.BooleanField()
cost = models.IntegerField()
status_of_apartment = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Payment_status(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Rent(models.Model):
id_client = models.ForeignKey(Client)
id_outlet = models.ForeignKey(Apartment)
start_time = models.DateField()
finish_time = models.DateField()
status = models.CharField(max_length=50)
class Payment(models.Model):
id_rent = models.ForeignKey(Rent)
id_payment_status = models.ForeignKey(Payment_status)
method_of_payment = models.CharField(max_length=50)
date_of_payment = models.DateField(True)
summ_of_payment = models.FloatField()
def __unicode__(self):
return self.id
And In view I want to write status payment for the rent.
I have payment 1.12.2015 250$
Apartment cost 125$ it's 2 month.
15.12.2015 - status active
25.06.2015 - status not active.
pseudo code:
rent = Rent.get(pk=1)
costApartment = rent.id_outlet.cost
active_payment = payment.count([payment.id_payment_status.name = "paid", id_rent = rent.id, data_of_payment.addMonth(summ_of_payment / costApartment) > now()]) > 0
You forgot the objects after the Rent, but I did it for you here and gave you some examples:
rent = Rent.objects.get(id=1)
apartment_cost = rent.id_outlet.cost
payment = Payment.objects.get(id_rent=rent)
date_of_payment = payment.date_of_payment
....
So the first one is to create a variable called rent and assign it to Rent with and id=1. With that I could easily get the cost of the Apartment since you have a ForeignKey in your Rent model to the Apartment model. So we went from Rent to the id_outlet which links us to the Apartment model, and from their we accessed the price. Easy right? ForeignKeys make them easier for you, you can jump from one place to another easily just by connecting them well, which I say you did pretty well! Hope that answered your question.
Try not to call your FK fields like client_id or rent_id as you did in your question, because you are referring the whole model Client and not just the client's id, so it's better to you client as the field. Same goes for the `rent_id.

Filtering a QuerySet With another QuerySet

Hi i'm not very good at English but i'll try to explain myself the best i could. I'm using python and Django to create a web project.
I have this 4 models (this is the best translation i can do of the tables and fields):
class Humans (models.Model):
name = models.CharField(max_length=15)
surname = models.CharField(max_length=15)
doc_num = models.CharField(max_length=11)
...
class Records (models.Model):
closing_state = models.CharField(max_length=2)
...
humans = models.ManyToManyField(Humans, through='Reco_Huma')
class Reco_Huma (models.Model):
id_record = models.ForeignKey(Records)
id_human = models.ForeignKey(Humans)
categorys = models.CharField(max_length=2)
reserv_identity = models.CharField(max_length=2)
repre_entity = models.CharField(max_length=2)
class Observations (models.Model):
id_record = models.ForeignKey(Records)
text = models.CharField(max_length=80)
category = models.CharField(max_length=2, choices=CAT)
Now given a doc_num from Humans, a text from Observations i want to get a QuerySet Of all the Records.
To clarify i first do this:
q1 = Reco_Huma.objects.filter(id_human.doc_num=x)
q2 = Observations.objects.filter(text=y)
both query-sets give me a list of id_record and then i want to connive that lists and filter the Records table with that id_record's
I hope you can understand me
Thanks in advance
To rephrase your query, you want all the Records associated with a certain Human and which have a certain Observation. So it should be:
result = Records.objects.filter(observations__text=y, humans__doc_num=x)
As a general rule, if you want to end up with a certain type of object, it helps to start from there in your query.

Categories