I'm trying to create an instance of "Partita" Model but I don't want to set manually the fields with a form; I need to set the fields (they are two ForeignKey) with a random integer that refers to the id of the Foreign Key.
This is for create a type of creator of football matches where "Partita" (match in italian) is composed by team1 and team2 (in my code "casa" and "trasferta") How can I do it?
I tried this but it throws: Page Not Found, No FantaSquadra matches the given query.
views.py:
def createPartite(request):
num1=0
num2=0
gior=0
while num1==num2:
num1 = str(random.randint(1,3))
num2 = str(random.randint(1,3))
if num1!=num2:
gior=gior+1
cas= get_object_or_404(FantaSquadra, pk=num1)
tra= get_object_or_404(FantaSquadra, pk=num2)
partita = Partita.creaP(cas,tra)
partita.save()
contesto = {
'partita': partita
}
return render(request, 'sondaggio/partite.html',contesto)
models.py:
class FantaSquadra(models.Model):
proprietario = models.ForeignKey(User, on_delete=models.CASCADE,unique=True)
nome_fantasquadra = models.CharField(max_length=200,unique = True)
punteggio = models.IntegerField(default=0)
def __str__(self):
return self.nome_fantasquadra
class Partita(models.Model):
giornata = models.IntegerField(default=1)
casa=models.ForeignKey(FantaSquadra,on_delete=models.CASCADE, related_name='fantasquadra_casa', unique=True)
traferta = models.ForeignKey(FantaSquadra, on_delete=models.CASCADE, related_name='fantasquadra_trasferta', unique=True)
def __str__(self):
return "giornata "+str(self.giornata)
def creaP(self,cas,trasfert):
self.casa = cas
self.traferta = trasfert
return self
Partita.objects.create(casa=cas, traferta=tra).