Sorry if it's a bad name for a title, but I'm not sure how to explain this. I would like to make a form for entry into the Captains model, however there needs to be a queryset filter so you can only select players from a user's FantasyTeam.
I have the models as follows:
class Player(models.Model):
player_id = models.IntegerField(primary_key=True)
team = models.ForeignKey(Team)
player_name = models.CharField(max_length=140)
position = models.CharField(max_length=10)
first_name = models.CharField(max_length=70)
last_name = models.CharField(max_length=70)
known_name = models.CharField(max_length=70,blank=True)
birth_date = models.DateField('birth date')
weight = models.IntegerField()
height = models.IntegerField()
jersey_num = models.IntegerField()
real_position = models.CharField(max_length=25)
join_date = models.DateField('join date')
country = models.CharField(max_length=30)
value = models.DecimalField(max_digits=3,decimal_places=1)
is_active = models.BooleanField(default=False)
def __str__(self):
return '%s (%s)' % (self.player_name,self.value)
class FantasyTeam(models.Model):
FANTASY_TEAM_ID = models.AutoField(primary_key=True)
team_name = models.CharField(max_length=25)
player1 = models.ForeignKey(Player, related_name='csplayer1')
player2 = models.ForeignKey(Player, related_name='csplayer2')
player3 = models.ForeignKey(Player, related_name='csplayer3')
player4 = models.ForeignKey(Player, related_name='csplayer4')
player5 = models.ForeignKey(Player, related_name='csplayer5')
player6 = models.ForeignKey(Player, related_name='csplayer6')
player7 = models.ForeignKey(Player, related_name='csplayer7')
player8 = models.ForeignKey(Player, related_name='csplayer8')
player9 = models.ForeignKey(Player, related_name='csplayer9')
player10 = models.ForeignKey(Player, related_name='csplayer10')
player11 = models.ForeignKey(Player, related_name='csplayer11')
player_sub_gk = models.ForeignKey(Player, related_name='cssubgk')
player_sub_1 = models.ForeignKey(Player, related_name='cssub1')
player_sub_2 = models.ForeignKey(Player, related_name='cssub2')
player_sub_3 = models.ForeignKey(Player, related_name='cssub3')
def __str__(self):
return '%s' % (self.team_name)
class Captains(models.Model):
fantasy_team = models.OneToOneField(ClassicSeasonFantasyTeam,primary_key=True)
captain = models.ForeignKey(Player, related_name='cscaptain')
vice_captain = models.ForeignKey(Player, related_name='csvicecaptain')
#Associates a user with a FantasyTeam
class ClassicSeasonUserTeam(models.Model):
CS_USER_TEAMS_ID = models.AutoField(primary_key=True)
fantasy_team = models.ForeignKey(ClassicSeasonFantasyTeam)
user = models.ForeignKey(User)
total_score = models.IntegerField(default=0)
season = models.ForeignKey(Season)
def __str__(self):
return '%s' % (self.user.username)
How can I achieve the queryset filter?
forms.py
class CaptainsForm(ModelForm):
class Meta:
model = ClassicSeasonCaptains
def __init__(self,*args,**kwargs):
super(ClassicSeasonCaptains,self).__init__(*args,**kwargs)
#filter to players that are only in the user's fantasy team
self.fields['captain'].queryset = ClassicSeasonFantasyTeam.objects.filter()????
self.fields['vice_captain'].queryset = ?????
If I understand correctly you want to limit the choices for a field in the form. The answer to that question is already given and is really good, see: https://stackoverflow.com/a/3420588/2583290
As for the Queryset filter itself, you want Players, so start with Player.objects.filter(). For the actual filter query you'll need to clean your code a bit first. It's would be overly complex because of how Players are linked to your FantasyTeam.
Consider having A class TeamPlayer with a role ("normal", "sub", "captain"). Read up in the django docs
PS: Avoid using plural class names. Use Captain instead of Captains.
PPS: Captain(s) should probably inherit from Player or a Person class rather than have a ForeignKey
Related
I have a model name Employee now i want to add a new fields in this model which will be a foreign key of Department model.I try to solve it the following way but i get error like
django.db.utils.IntegrityError: The row in table 'employee_verification_employee' with primary key 'UP-0319001' has an invalid foreign key: employee_verification_employee.department_id contains a value '03' that does not have a corresponding value in employee_verification_department.id.
class Department(models.Model):
name = models.CharField(max_length=100)
id = models.CharField(primary_key=True,max_length=10)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.CharField(max_length=100,choices = Departments)
date_of_joining = models.DateField()
employeed = models.BooleanField(default = True)
email = models.EmailField(max_length = 254)
blood_group = models.CharField(max_length=50)
designation = models.CharField(max_length=100)
image = models.ImageField(upload_to='employee_images',default = "")
number = PhoneField(blank=True, help_text='Enter Contact Number')
emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
id = models.CharField(primary_key=True, max_length=200)
department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)
def save(self, *args, **kwargs):
if not self.id:
nth_member = Employee.objects.filter(department = self.department).count()+1
self.id = "UP-" + self.department + self.date_of_joining.strftime("%y")+"{:03d}".format(nth_member)
print(self.id)
super(Employee, self).save(*args, **kwargs)
def __str__(self):
return self.name + "--"+ self.designation``
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/xdRMd.png
As #trigo said, all you need is:
class Department(models.Model):
name = models.CharField(max_length=100)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.CharField(max_length=100,choices = Departments)
date_of_joining = models.DateField()
employeed = models.BooleanField(default = True)
email = models.EmailField(max_length = 254)
blood_group = models.CharField(max_length=50)
designation = models.CharField(max_length=100)
image = models.ImageField(upload_to='employee_images',default = "")
number = PhoneField(blank=True, help_text='Enter Contact Number')
emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)
And Django will take care of the rest (ids).
My lab has a models.py as below:
class Book(models.Model):
isbn = models.CharField(max_length=10, unique=True)
name = models.CharField(max_length=100)
published_year = models.IntegerField()
total_qty = models.IntegerField()
current_qty = models.IntegerField()
max_duration = models.IntegerField()
author = models.ForeignKey(Author, on_delete=models.PROTECT)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
def __str__(self):
return self.name
class BookCopy(models.Model):
class Status:
AVAILABLE = 1
BORROW =2
LOST = 3
barcode = models.CharField(max_length=30, unique=True)
buy_date = models.DateField(null=True, blank=True)
status = models.IntegerField()
book = models.ForeignKey(Book, on_delete=models.PROTECT)
def __str__(self):
return self.barcode
class User(models.Model):
username = models.CharField(max_length=30, unique=True)
fullname = models.CharField(max_length=100, null=True)
phone = models.CharField(max_length=10, null=True)
def __str__(self):
return self.fullname
class BookBorrow(models.Model):
class Status:
BORROWING = 1
RETURNED = 2
borrow_date = models.DateField()
deadline = models.DateField()
return_date = models.DateField(null=True)
status = models.IntegerField()
book_copy = models.ForeignKey(BookCopy, on_delete=models.PROTECT)
book_name = models.ForeignKey(Book, on_delete=models.PROTECT)
user = models.ForeignKey(User, on_delete=models.PROTECT)
And i wrote the api for borrow_book function like below:
#csrf_exempt
def muon_sach(request):
body = request.POST
username = body.get('username')
barcode = body.get('barcode')
user = User.objects.filter(username=username).first()
bookcopy = BookCopy.objects.filter(barcode = barcode).first()
if not user:
return HttpResponse(json.dumps({
'error':"Nguoi dung khong ton tai"
}))
if not bookcopy:
return HttpResponse(json.dumps({
'error':"ma sach khong ton tai"
}))
book_borrow = BookBorrow()
# resp = []
book_borrow.user = user
book_borrow.book_copy = bookcopy
book_borrow.borrow_date = datetime.now()
book_borrow.deadline = datetime.now() + timedelta(days=bookcopy.book.max_duration)
book_borrow.status = BookBorrow.Status.BORROWING
book_borrow.book_name = bookcopy.book.name
book_borrow.save()
bookcopy.status = BookCopy.Status.BORROW
bookcopy.save()
bookcopy.book.current_qty -=1
bookcopy.book.save()
return HttpResponse(json.dumps({'success':True}))
however when i test with postman (give username and barcode), it gets the error
xxx "BookBorrow.book_name" must be a "Book" instance."
Could you please advise where incorrect and assist me correct it ? Appreciate for any assist
You have to do the following:
#csrf_exempt
def muon_sach(request):
# ... more code here
bookcopy = BookCopy.objects.filter(barcode = barcode).first()
book_borrow.book_name = bookcopy.book
book_borrow.save()
# ... more code here
return HttpResponse(json.dumps({'success':True}))
So in the definition of your model you can see that book_name has the following structure:
class BookBorrow(models.Model):
# ... More code here
book_name = models.ForeignKey(Book, on_delete=models.PROTECT)
user = models.ForeignKey(User, on_delete=models.PROTECT)
It is clear that BookBorrow.book_name must accept a Book instance. So when you pass in you code book_borrow.book_copy = bookcopy it is passing a BookCopy instance so that's the error.
borrow_copy.book is the appropiate.
You have specified book_name to be a Foreign Key to Book, and you try to assign to it the book.name value.
Either you need to set this field as a CharField or you need to rename the field from book_name to book and use book_borrow.book = bookcopy.book
I am a beginner in django. Following is my Attendance Management App.
This is my models.py.
from django.db import models
class Subject(models.Model):
subject_name = models.CharField(max_length=20)
#attendance = models.ForeignKey(Attendance, on_delete =
models.DO_NOTHING)
attendance = models.IntegerField(default=0)
def __str__(self):
return self.subject_name
class Section(models.Model):
section_name = models.CharField(max_length=20)
subject = models.ManyToManyField(Subject)
def __str__(self):
return self.section_name
class Student(models.Model):
rollno = models.IntegerField()
name = models.CharField(max_length=20)
section = models.ForeignKey(Section, on_delete = models.DO_NOTHING,
default=0)
def __str__(self):
return str(self.rollno) + self.name
class Teacher(models.Model):
#teacher_name = models.CharField(max_length=20)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
#section_name = models.CharField(max_length=10)
#subject_name = models.CharField(max_length=30)
def __str__(self):
return self.section.section_name+' '+self.subject.subject_name
class TeacherList(models.Model):
teacher_name = models.CharField(max_length=20)
teacher = models.ManyToManyField(Teacher)
def __str__(self):
return self.teacher_name
The line below is not working in views.py
student = models.Student.objects.get(rollno = sroll)
student.section.subject.get(subject_name = 'java').attendance += 1
student.save()
This view is called from a template when a button is clicked to add attendance of a student.
The attendance in above code is not modified. Please help me out.
You're saving the student, instead of the subject.
student = models.Student.objects.get(rollno = sroll)
subject = student.section.subject.get(subject_name='java')
subject.attendance += 1
subject.save()
Or, better, do the update directly in one go:
student.section.subject.filter(subject_name='java').update(attendance=F('attendance')+1)
and there's no need to save at all.
class Team(models.Model):
team_name = models.CharField(max_length=50, null=False)
def __str__(self):
return self.team_name
class Tournament(models.Model):
types = (
('Round', 'Round'),
('Knockout', 'Knockout'),
)
teams = models.ManyToManyField(Team, related_name='tournament_teams')
tournament_name = models.CharField(max_length=50, null=False)
tournament_type = models.CharField(choices=types, max_length=40, null=False)
def __str__(self):
return self.tournament_name
class MatchRound(models.Model):
team_a_id = models.ForeignKey(Team, related_name="team_a")
team_b_id = models.ForeignKey(Team)
date = models.DateTimeField(null=True)
team_a_score = models.IntegerField(null=True)
team_b_score = models.IntegerField(null=True)
tournament_id = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True)
#receiver(post_save, sender=Tournament)
def create_match_round(sender, **kwargs):
type = kwargs.get('instance').tournament_type
if type == 'Round' and kwargs.get('created', False):
teams = kwargs.get('instance').teams.all()
schedule = create_schedule(teams)
for round in schedule:
for match in round:
team_a_id = match[0]
team_b_id = match[1]
tournament_id = kwargs.get('instance')
game = MatchRound.objects.create(team_a_id=team_a_id, team_b_id=team_b_id,
tournament_id=tournament_id)
I am trying to create a schedule for a tournament. So, I set up a trigger on MatchRound model and I am trying to get the teams of the tournament when it's created. However, the following line
teams = kwargs.get('instance').teams.all()
returns to an empty query set. I couldn't figure it out the problem.
How can I get the foreign key values? I have a common vehicle model that links to the year, series, engine type, body style, transmission and drive train...all as foreign keys. I'd like to get the values of these fields for my app, but I'm stuck as to how I'd go about them. Any ideas will be highly appreciated.
class Model(models.Model):
model = models.CharField(max_length=15, blank=False)
manufacturer = models.ForeignKey(Manufacturer)
date_added = models.DateField()
def __unicode__(self):
name = ''+str(self.manufacturer)+" "+str(self.model)
return name
class Year(models.Model):
ALPHA_NUMERIC_CHOICES = (
('1', 'Numeric'),
('A', 'Alphabetic'),
)
year = models.PositiveSmallIntegerField()
position_7_char = models.CharField(max_length=1, choices=ALPHA_NUMERIC_CHOICES)
position_10 = models.CharField(max_length=1, blank=False)
def __unicode__(self):
return unicode(self.year)
class Series(models.Model):
series = models.CharField(max_length=20, blank=True)
model = models.ForeignKey(Model)
date_added = models.DateField()
def __unicode__(self):
name = str(self.model)+" "+str(self.series)
return name
class CommonVehicle(models.Model):
year = models.ForeignKey(Year)
series = models.ForeignKey(Series)
engine = models.ForeignKey(Engine)
body_style = models.ForeignKey(BodyStyle)
transmission = models.ForeignKey(Transmission)
drive_train = models.ForeignKey(DriveTrain)
def __unicode__(self):
name = ''+str(self.year)+" "+str(self.series)
return name
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
def __unicode__(self):
return self.stock_numberodels.ForeignKey(CommonVehicle)
You need the actual IDs? Try something like my_vehicle_ref.series.id.
Also, I hope you know that the series attribute right there is really an instance of Series, so you could access any of it's properties, e.g., my_vehicle_ref.series.model.model.