I'm working on a django based backend.
I have a Submentor model. This model is going to have a list of names associated with it. So, I made a model called List. they both have a manytoMany relationship. Now, I made another model called names. This has a ManytoMany relationship with List. The list will have many names. Each Submentor will have one List each.
After coding when I try to add a value in The list from admin console I get core.Name.none instead of the name in my Submentors list.
What am I doing wrong?
code of models :-
class Names(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True,null=True)
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class SAccepted_list(models.Model):
saccepted_name = models.ManyToManyField(Names,blank =True, related_name='saccepted_name')
def __str__(self):
return str(self.saccepted_name)
class SPending_list(models.Model):
spending_name = models.ManyToManyField(Names,blank =True, related_name='spending_name')
def __str__(self):
return str(self.spending_name)
class SRejected_list(models.Model):
srejected_name = models.ManyToManyField(Names,blank =True, related_name='srejected_name')
def __str__(self):
return str(self.srejected_name)
class SubMentor(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
mentee_pref_count = models.IntegerField(default=3, verbose_name='Preferred mentee count')
rating = GenericRelation(Rating, related_query_name='Submentor')
skills = models.ManyToManyField(Skill, blank=True, related_name='subskills')
courses = models.ManyToManyField(Course, blank=True, related_name='subcourses')
projects = models.ManyToManyField(Project, blank=True, related_name='subprojects')
saccepted_list = models.ManyToManyField(SAccepted_list,blank=True,related_name='saccepted_list')
spending_list = models.ManyToManyField(SPending_list, blank=True,related_name='spending_list')
srejected_list = models.ManyToManyField(SRejected_list, blank=True,related_name='srejected_list')
def __str__(self):
return self.user.get_full_name()
def get_mentee_count(self, *args, **kwargs):
if self.trainees.exists():
return self.trainees.count()
else:
return 0
class Accepted_list(models.Model):
accepted_name = models.ManyToManyField(Names,blank =True, related_name='accepted_name')
# saccepted_name = models.ManyToManyField(Names,blank =True, related_name='saccepted_name')
def __str__(self):
return str(self.accepted_name)
class Pending_list(models.Model):
pending_name = models.ManyToManyField(Names,blank =True, related_name='pending_name')
# spending_name = models.ManyToManyField(Names,blank =True, related_name='spending_name')
def __str__(self):
return str(self.pending_name)
class Rejected_list(models.Model):
rejected_name = models.ManyToManyField(Names,blank =True, related_name='rejected_name')
# srejected_name = models.ManyToManyField(Names,blank =True, related_name='srejected_name')
def __str__(self):
return str(self.rejected_name)
class Mentor(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
score = models.FloatField(default=0, blank=True, null=True)
mentee_pref_count = models.IntegerField(default=5, verbose_name='Preferred menteee count')
rating = GenericRelation(Rating, related_query_name='mentor')
skills = models.ManyToManyField(Skill, blank=True, related_name='skills')
accepted_list = models.ManyToManyField(Accepted_list,blank=True,related_name='accepted_list')
pending_list = models.ManyToManyField(Pending_list, blank=True,related_name='pending_list')
rejected_list = models.ManyToManyField(Rejected_list, blank=True,related_name='rejected_list')
def __str__(self):
return self.user.get_full_name()
def get_mentee_count(self, *args, **kwargs):
if self.trainees.exists():
return self.trainees.count()
else:
return 0
picture of me adding names direct through admin console:-
Thank you.
Ok, I solved my problem. It was wrong of me in the first place to use m2m and then another to make a list.
Instead I used only 1 m2m relationship with Lists and then made a property of them to be charfield. Now it's working properly.
Thanks :)
Related
I have created different models and in the Division model I am taking reference of many models and their primary key is referenced as a foreign key in Division Model. I have declared courses as a model attribute in the Batch Model.
This is my models.py file
class lab_load(models.Model):
lab_code = models.CharField(max_length=10,null=True)
subject_name = models.CharField(max_length=100,null=True)
subject_abv = models.CharField(max_length=10,null=True)
lab_load = models.IntegerField(null=True)
semester = models.IntegerField(null=True)
max_numb_students = models.CharField(max_length=65,null=True)
instructors = models.ManyToManyField(Instructor)
def __str__(self):
return f'{self.lab_code} {self.subject_name} {self.subject_abv}'
class Batch(models.Model):
bat_name = models.CharField(max_length=50)
courses = models.ManyToManyField(lab_load)
#property
def get_courses(self):
return self.courses
def __str__(self):
return self.bat_name
class Division(models.Model):
division_id = models.CharField(max_length=25, primary_key=True)
batch = models.ForeignKey(Batch, on_delete=models.CASCADE,blank=True, null=True)
num_lab_in_week = models.IntegerField(default=0)
course = models.ForeignKey(lab_load, on_delete=models.CASCADE, blank=True, null=True)
lab_time = models.ForeignKey(LabTime, on_delete=models.CASCADE, blank=True, null=True)
room = models.ForeignKey(LabRoom,on_delete=models.CASCADE, blank=True, null=True)
instructor = models.ForeignKey(Instructor, on_delete=models.CASCADE, blank=True, null=True)
def set_labroom(self, labroom):
division = Division.objects.get(pk = self.division_id)
division.room = labroom
division.save()
def set_labTime(self, labTime):
division = Division.objects.get(pk = self.division_id)
division.lab_time = labTime
division.save()
def set_instructor(self, instructor):
division = Division.objects.get(pk=self.division_id)
division.instructor = instructor
division.save()
My views.py file
class Data:
def __init__(self):
self._rooms = Room.objects.all()
self._meetingTimes = MeetingTime.objects.all()
self._instructors = Instructor.objects.all()
self._courses = Course.objects.all()
self._depts = Department.objects.all()
self._labrooms = LabRoom.objects.all()
self._labTimes = LabTime.objects.all()
self._labcourses = lab_load.objects.all()
self._bats = Batch.objects.all()
def get_rooms(self): return self._rooms
def get_labs(self): return self._labs
def get_labrooms(self): return self._labrooms
def get_instructors(self): return self._instructors
def get_courses(self): return self._courses
def get_depts(self): return self._depts
def get_labcourses(self): return self._labcourses
def get_bats(self): return self._bats
def get_meetingTimes(self): return self._meetingTimes
def get_labTimes(self): return self._labTimes
Under different class: Created class LabSchedule under that I have created function initialize.
def initialize(self):
divisions = Division.objects.all()
for division in divisions:
bat = Division.batch
n = division.num_lab_in_week
if n <= len(LabTime.objects.all()):
labcourses = bat.courses.all() <------ Error in this line ------->
for labcourse in labcourses:
for i in range(n // len(labcourses)):
crs_inst = labcourse.instructors.all()
newClass = Classlab(self._classNumb, bat, division.division_id, labcourse)
self._classNumb += 1
newClass.set_labTime(data.get_labTimes()[rnd.randrange(0, len(LabTime.objects.all()))])
newClass.set_labroom(data.get_labrooms()[rnd.randrange(0, len(data.get_labrooms()))])
newClass.set_instructor(crs_inst[rnd.randrange(0, len(crs_inst))])
self._classes.append(newClass)
else:
n = len(LabTime.objects.all())
labcourses = bat.courses.all()
for labcourse in labcourses:
for i in range(n // len(labcourses)):
crs_inst = labcourse.instructors.all()
newClass = Classlab(self._classNumb, bat, division.division_id, labcourse)
self._classNumb += 1
newClass.set_labTime(data.get_labTimes()[rnd.randrange(0, len(LabTime.objects.all()))])
newClass.set_labroom(data.get_labrooms()[rnd.randrange(0, len(data.get_labrooms()))])
newClass.set_instructor(crs_inst[rnd.randrange(0, len(crs_inst))])
self._classes.append(newClass)
return self
I am using a genetic algorithm to schedule classes and labs.
Can anyone solve my error it will be helpful, Thank You.
I have this Error :
IntegrityError at /api/post_flight_schedule/
NOT NULL constraint failed: flights_tailnumber.aircraft_type_id
When I try to add a new PosFlightSchedule object to DB over http://127.0.0.1:8000/api/pos_flight_schedule (Website/APIView)
I have the below serializer :
class PosFlightScheduleModelSerializer(ModelSerializer):
class Meta:
model = PosFlightSchedule
fields = ['pos_route_id', 'tail_number', 'pos_flight_number', 'pos_flight_departure_time', 'pos_flight_date',
'pax_count']
class PosFlightScheduleSerializer(serializers.Serializer):
pos_route_id = serializers.CharField(source='pos_route_id.route_id', read_only=False)
tail_number = serializers.CharField(source='tail_number.tail_number', read_only=False)
pos_flight_number = serializers.CharField(source='pos_flight_number.flight_number', read_only=False)
pos_flight_departure_time = serializers.CharField(source='pos_flight_departure_time.flight_departure_time', allow_null=True,
read_only=False)
pos_flight_date = serializers.CharField(source='pos_flight_date.flight_date', read_only=False)
pax_count = serializers.IntegerField(read_only=False)
def create(self, validated_data):
tail_number_data = validated_data.pop("tail_number")
tail_number = TailNumber.objects.create(**tail_number_data)
flight_number_data = validated_data.pop("pos_flight_number")
flight_number = FlightSchedule.objects.create(**flight_number_data)
flight_departure_time_data = validated_data.pop("pos_flight_departure_time")
print "DEP_TIME" + str(flight_departure_time_data)
flight_departure_time = FlightSchedule.objects.create(**flight_departure_time_data)
route_id_data = validated_data.pop("pos_route_id")
route_id = FlightScheduleDetail.objects.create(**route_id_data)
flight_date_data = validated_data.pop("pos_flight_date")
flight_date = FlightScheduleDetail.objects.create(**flight_date_data)
pax_count = validated_data.pop("pax_count")
schedule_obj = PosFlightSchedule.objects.create(**validated_data)
# if tail_number:
schedule_obj.set_tail_number(tail_number)
schedule_obj.set_pos_flight_number(flight_number)
schedule_obj.set_pos_flight_departure_time(flight_departure_time)
schedule_obj.set_pos_route_id(route_id)
schedule_obj.set_pos_flight_date(flight_date)
schedule_obj.set_pax_count(pax_count)
schedule_obj.save()
return schedule_obj
def update(self, instance, validated_data):
tail_number = validated_data.pop("tail_number")
flight_number = validated_data.pop("pos_flight_number")
flight_departure_time = validated_data.pop("pos_flight_departure_time")
route_id = validated_data.pop("pos_route_id")
flight_date = validated_data.pop("pos_flight_date")
pax_count = validated_data.pop("pax_count")
instance.__dict__.update(validated_data)
if tail_number:
instance.set_tail_number(tail_number)
if flight_number:
instance.set_pos_flight_number(flight_number)
if flight_departure_time:
instance.set_pos_flight_departure_time(flight_departure_time)
if route_id:
instance.set_pos_route_id(route_id)
if flight_date:
instance.set_pos_flight_date(flight_date)
if pax_count:
instance.set_pax_count(pax_count)
instance.save()
return instance
The model of the field which is giving error looks like :
class TailNumber(models.Model):
tail_number_id = models.AutoField(null=False, primary_key=True)
tail_number = models.CharField(max_length=20, null=False, blank=False, unique=True)
aircraft_type = models.ForeignKey(AircraftType, null=False, blank=False)
def __unicode__(self):
return u'%s' % self.tail_number
class Meta:
verbose_name_plural = "Tail Numbers"
I am not understanding what is going wrong here.
The error you get is probably due to the fact that the dictionary tail_number_data does not contain the keyword aircraft_type, which is expected by TailNumber.objects to create the row in the db, since you defined it with no possibility to be null
aircraft_type = models.ForeignKey(AircraftType, null=False, blank=False)
^^^^^
Check that the key "aircraft_type" does exist in the dictionary tail_number_data, or allow for it to be null. Furthermore, if you consider the latter option and that this information is supposed to come from a UI, you may also want to allow for aircraft_type to be blank. See differentiate null=True, blank=True in django for details.
Okay, so I'm sure i'm making a simple error here but I'm at a loss as to what it might be at this point or where to even begin to find the cause of this failing...
I have 5 models, set up like so:
class Keyword(models.Model):
key = models.CharField(max_length=2000, unique=True)
def __str__(self):
return self.key
class Entries(models.Model):
name = models.CharField("Name", max_length=200)
updated = models.DateTimeField("Last Updated", auto_now=True)
key_list = models.ManyToManyField(Keyword, blank=True, verbose_name="Keywords")
description = models.TextField("Description", blank=True)
class Meta:
abstract = True
class Employee(Entries):
uid= models.SlugField("UserID", max_length=6, unique=True, blank=True)
manager = models.SlugField("Manager's UserID", max_length=6)
def __str__(self):
return self.name
class Vendor(Entries):
company = models.CharField("Vendor Company", max_length=200)
email = models.EmailField("Vendor's Company Email Address", max_length=254, unique=True)
vend_man_name = models.CharField("Manager's Name", max_length=200)
vend_man_email = models.EmailField("Manager's Email Address", max_length=254)
def __str__(self):
return self.name
class Application(Entries):
app_url = models.URLField("Application URL", max_length=800, unique=True)
def __str__(self):
return self.name
class Machine(Entries):
address = models.CharField("Machine Address", max_length=800, unique=True)
phys_loc = models.TextField("Physical Location", blank=True)
def __str__(self):
return self.name
and my templatetag to display the data is thus:
#register.inclusion_tag('Labswho/key_cloud.html')
def key_cloud(keys_selected=''):
key_list = Keyword.objects.all()
for entry in key_list:
counter = Keyword.objects.filter(employee__key_list__key__contains=entry).distinct().count()
counter += Keyword.objects.filter(vendor__key_list__key__contains=entry).distinct().count()
counter += Keyword.objects.filter(application__key_list__key__contains=entry).distinct().count()
counter += Keyword.objects.filter(machine__key_list__key__contains=entry).distinct().count()
entry.append({'counter': counter})
context = {'key_list': key_list}
return context
but it keeps throwing me errors.
What I want it to do is to grab a count of the instances of each keyword on each model, add those instances together, and then give me a number I can reference in the template. My end goal is that I can use that number to set the font size so that keywords used more frequently will be visibly larger then ones used less frequently. I think what I want is for it to set a dictionary within each entry of my key_list, which i can then call for that number in the template when setting the font size. Not sure if i'm over-complicating this or how to fix it at this point so that it actually works...
(This is using Python 3.5 & Django 1.10)
I'm playing around in Django, and wondering if there is a way to loop through instances of two different models I have created?
/ models.py:
class Tran(models.Model):
name = models.CharField(max_length=300)
description = models.CharField(max_length=2000)
type = models.ForeignKey(TransactionType)
def __str__(self):
return self.name
class DocLink(models.Model):
trann = models.ForeignKey(Transaction)
t_link = models.CharField(max_length=2000)
t_display = models.CharField(max_length=1000)
p_display = models.CharField(max_length=300)
p_link = models.CharField(max_length=2000)
def __str__(self):
return self.link
What I want to do:
Look through each of the Tran instances and create a default value for the links/displays in the DocLink table instead of doing it manually.
Is there anyway I can be pointed in the right direction?
If you want to set links/displays default value in DocLink instance based on trann field you can override model's save method.
For example following code shows how to set t_link if it doesn't have a value:
class DocLink(models.Model):
trann = models.ForeignKey(Transaction)
t_link = models.CharField(max_length=2000)
t_display = models.CharField(max_length=1000)
p_display = models.CharField(max_length=300)
p_link = models.CharField(max_length=2000)
def __str__(self):
return self.link
def save(self, *args, **kwargs):
if not self.t_link:
pass # TODO set self.t_link based on trann
super(DocLink, self).save(*args, **kwargs)
Also you can change model's trann field to:
trann = models.ForeignKey(Transaction, related_name="doclinks")
And then access to all DocLinks of a Tran with:
# t is an instance of Tran class
t.doclinks.all()
So you can loop through this list and do what you want.
I'm asking if I set up the create method up correctly. Or does it need to be added for the other two models as well? How would this be changed?
class PointModel(models.Model):
x = models.IntegerField()
y = models.IntegerField()
index = models.IntegerField()
class DatetimeRangeModel(models.Model):
start_datetime = models.CharField(max_length=14)
end_datetime = models.CharField(max_length=14)
class PlanModel(models.Model):
data_number = models.IntegerField()
data_datetime_range = models.ForeignKey(DatetimeRangeModel, blank=True, null=True, on_delete=models.SET_NULL)
data_polygon = models.ForeignKey(PointModel, blank=True, null=True, on_delete=models.SET_NULL)
#classmethod
def create(cls, data_number, data_datetime_range, data_polygon):
plan = cls(data_number=data_number, data_datetime_range = data_datetime_range,
data_polygon=data_polygon)
return plan
EDIT: I change the structure which fixed the undefined and added some logic that prevents the PlanModel from being deleted with the "blank=True, null=True, on_delete=models.SET_NULL"
Does this look right?
see the docs for creating objects
#classmethod
def create(cls, title):
book = cls(title=title)
# do something with the book
return book
there's no much reason to add those unless you have something to add there on the # do something with the book line
EDIT: instead of calling create you're usually do:
plan = PlanModel(data_number=1, ....)
plan.save()
or sometimes:
plan = PlanModel()
plan.data_number=1
...
plan.save()