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.
Related
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 have a booking system for bank line :
this is my model for the customer:
class Customer(models.Model):
customer_bank = models.ForeignKey('Bank', on_delete=models.SET_NULL,related_name='coustmer_bank' ,null=True)
customer_branch = models.ForeignKey('Branch', on_delete=models.SET_NULL,related_name='coustmer_branch',null=True)
booking_id = models.CharField(max_length=120, blank= True,default=increment_booking_number)
identity_type = models.ForeignKey('IdentityType',on_delete=models.SET_NULL,related_name='identity_type',null=True)
identity_or_passport_number = models.CharField(max_length=20)
bank_account_no = models.CharField(max_length=15)
Done = models.BooleanField(default=False)
booking_date_time = models.DateTimeField(auto_now_add=True, auto_now=False)
Entrance_date_time = models.DateTimeField(auto_now_add=False, auto_now=True)# Must be modified to work with Entrance Date and Time
def __str__(self):
return self.booking_id
I need to generate a random value for booking_id field depends on bank_number and the branch_number and the Customer id so how can I do that? help please
You can overide the save method of the model
class Customer(models.Model):
customer_bank = models.ForeignKey('Bank', on_delete=models.SET_NULL,related_name='coustmer_bank' ,null=True)
customer_branch = models.ForeignKey('Branch', on_delete=models.SET_NULL,related_name='coustmer_branch',null=True)
booking_id = models.CharField(max_length=120, blank= True,default=increment_booking_number)
identity_type = models.ForeignKey('IdentityType',on_delete=models.SET_NULL,related_name='identity_type',null=True)
identity_or_passport_number = models.CharField(max_length=20)
bank_account_no = models.CharField(max_length=15)
Done = models.BooleanField(default=False)
booking_date_time = models.DateTimeField(auto_now_add=True, auto_now=False)
Entrance_date_time = models.DateTimeField(auto_now_add=False, auto_now=True)# Must be modified to work with Entrance Date and Time
def __str__(self):
return self.booking_id
def get_booking_id(self):
bank_number = self.bank_number
branch_number = self.branch_number
id = # logic for calculating boking ID from bank_number, branch_number and other fields accessible from self.<field_name>
return id
def save(self, *args, **kwargs):
self.booking_id = self.get_booking_id()
super(Customer, self).save(*args, **kwargs)
how to get status_updation and status_date respect to the order_number
class customer_database(models.Model):
customer_id = models.CharField(max_length=20, unique=True)
customer_name = models.CharField(max_length=20)
customer_email = models.EmailField()
def __str__(self):
return self.customer_id
class order_database(models.Model):
order_number = models.CharField(max_length=10, unique=True, primary_key=True)
order_timestamp = models.DateTimeField()
order_consignment_number = models.CharField(max_length=20)
order_customer = models.ForeignKey(customer_database, on_delete=models.CASCADE)
def __str__(self):
return self.order_number
class track_database(models.Model):
order_status = models.ForeignKey(order_database, on_delete=models.CASCADE)
status_updation = models.CharField(max_length=30)
status_timestamp = models.DateTimeField()
def __str__(self):
return self.status_updation
Try
query_order_number = '1234'
tracker = track_database.objects.filter(order_status.order_number = query_order_number)
print(tracker.status_updation)
print(tracker.status_timestamp)
Let me know if this doesn't work
Or you could go via the order number:
query_order_number = '1234'
order = order_database.objects.filter(order_number = query_order_number)
print(order.track_database.status_updation)
print(order.track_database.status_timestamp)
In Django 1.6.1 I have a vehicle model which might zero or up to 2 traded-in units. Every time I edit any record, whether the change is trade-in instance #1 or instance 2, both records are updated with values instance #2.
Vehicle model:
class Vehicle(models.Model):
stock = models.CharField(max_length=10, blank=False, db_index=True)
vin = models.CharField(max_length=17, blank=False, db_index=True)
#vinlast8 = models.CharField(max_length=8, blank=False, db_index=True)
make = models.CharField(max_length=15, blank=False)
model = models.CharField(max_length=15, blank=False)
year = models.CharField(max_length=4, blank=False)
registry = models.IntegerField(blank=True, verbose_name='Reg #', null=True)
plate = models.CharField(blank=True, null=True, max_length=10)
tagno = models.IntegerField(blank=True, null=True, verbose_name='Tag #')
tag_exp = models.DateField(blank=True, null=True, verbose_name='Tag Exp')
Tradein model:
class TradeIn(Vehicle):
TradeInVehicle = (
(1, 'First vehicle'),
(2, 'Second vehicle'),
)
vehicle_sale = models.ForeignKey(VehicleSale)
tradeinpos = models.IntegerField(choices=TradeInVehicle)
lienholder = models.CharField(max_length=15, blank=True, null=True, verbose_name='L/holder')
lhdocrequested = models.DateField(blank=True, null=True, verbose_name='D/Requested')
lhdocreceived = models.DateField(blank=True, null=True, verbose_name='D/Received')
class Meta:
db_table = 'tradein'
def __unicode__(self):
return self.stock
def save(self, *args, **kwargs):
self.stock = self.stock.upper()
self.vin = self.vin.upper()
return super(TradeIn, self).save(*args, **kwargs)
The related sections on view is:
These sections are related to request.GET
current_vehicle = VehicleSale.objects.get(pk=pk)
tradeIns = current_vehicle.tradein_set.all().order_by('tradeinpos')
# Also add tradein_form to t_data so it can be rendered in the template
t_count = tradeIns.count()
if t_count == 0:
t_data['tradein1_form'] = TradeInForm()
t_data['tradein2_form'] = TradeInForm()
if t_count >= 1 and tradeIns[0] and tradeIns[0].tradeinpos == 1:
t_data['tradein1_form'] = TradeInForm(instance=tradeIns[0])
t_data['tradein2_form'] = TradeInForm()
if t_count == 2 and tradeIns[1] and tradeIns[1].tradeinpos == 2:
t_data['tradein2_form'] = TradeInForm(instance=tradeIns[1])
Now these are related to request.POST:
if 'tradein-form' in request.POST:
if tradeIns.count() > 0:
if tradeIns[0]:
tradein1_form = TradeInForm(request.POST, instance=tradeIns[0])
if tradein1_form.is_valid():
tradein1_form.save()
if tradeIns[1]:
tradein2_form = TradeInForm(request.POST, instance=tradeIns[1])
if tradein2_form.is_valid():
tradein2_form.save()
While reviewing contents of request.POST, it does contain any change I make in either instance. But always, the 2nd instance is saved.
What am I missing or have wrong?
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.