How to call a class attribute in another Django class

Asked

Viewed 721 times

2

I’m trying to create classes that will relate in a certain way. The idea is to be a game in which the player will have some options of choice and then your score is based on the score of your choices(kind of a Fantasy game).

For example:

class PrimeiroConjunto(models.Model):
    nome = models.CharField(max_length=255, null=False)
    pontuacao = models.FloatField(max_length=4, null=False)

class SegundoConjunto(models.Model):
    nome = models.CharField(max_length=255, null=False)
    pontuacao = models.FloatField(max_length=4, null=False)

class TerceiroConjunto(models.Model):
    nome = models.CharField(max_length=255, null=False)
    pontuacao = models.FloatField(max_length=4, null=False)

class Perfil(models.Model):
    nome = models.CharField(max_length=255, null=False)
    primeiraEscolha = models.ForeignKey(PrimeiroConjunto)
    segundaEscolha = models.ForeignKey(SegundoConjunto)
    terceiraEscolha = models.ForeignKey(TerceiroConjunto)

Then the Profile class would have a relationship with 3 other classes (which have different elements among themselves). And it would be necessary to access the score of each choice.

Except that I don’t know how to relate these classes by adding directly to the database, for example, let’s say that in the Primeset I have 3 elements:

Pedro - 100 Points

Alvaro - 70 Points

Bruno - 150 Points

and now I want to add a profile in the bank that will the choice of Primeiroconjunto would be Alvaro for example, how can I do this?

Because the only way I know so far to add an item in the database is manually via command prompt, for example:

>>>from abc.models import Perfil
>>>perfil = Perfil(nome='Gabriel', ???)
>>>perfil.save()

So, in doing so, what would I put in place of the "???" to associate Gabriel’s profile with Alvaro’s class profile PrimeiroConjunto, to access your score,

1 answer

2


You can put the instance to the object itself. Example:

>>> from abc.models import Perfil, PrimeiroConjunto
>>> conjunto = PrimeiroConjunto.objects.get(nome='Alvaro')
>>> perfil = Perfil(nome='Gabriel', primeiraEscolha=conjunto)
>>> perfil.save()

You can also add items in the bank using the views, doesn’t have to be in the prompt. But then they will usually be associated with forms(Forms). You can find more details here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.