i have Match and Game table, i want to choose players who will play in this match (bacause a team include more than 5 players. However a match play 5vs5)
class Match(models.Model):
name=models.CharField(max_length=255)
slug=models.SlugField(unique=True,max_length=255)
team1=models.ForeignKey('Team',related_name='team1',on_delete=models.PROTECT)
team2=models.ForeignKey('Team',related_name='team2',on_delete=models.PROTECT)
class Game(models.Model):
name = models.CharField(max_length=255)
match = models.ForeignKey(Match, on_delete=models.CASCADE)
team1players=models.ManyToManyField(match.team1.player.all())
team2players=models.ManyToManyField(match.team1.player.all())
Error: 'ForeignKey' object has no attribute 'team1'
Instead of having team1players and team2players in your Game model, you can add a ForeignKey field called something like current_game in your Player model and dynamically assign the current Game object to each 5 players from a team. Here is an example:
# models.py, Player model
class Player(models.Model):
name = models.CharField(max_length=255)
team = models.ForeignKey(Team)
# ... other fields ...
current_game = models.ForeignKey(Game, blank=True, null=True, related_name='current_players')
# ------------------------------------------------
# views.py
game = Game(name='Sample game')
# some operations
player1.current_game = game
player1.save()
game.save()
# You can access for current players in the game in team order like:
current_players_in_game = game.current_players.values('team', 'name').order_by('team')
Related
In order to make the problem easier to understand, I am writing the codes as short as possible here.
models.py:
----------
class Room(models.Model):
room_no = models.CharField()
class Unit(models.Model):
unit_name = models.CharField()
room = models.ManyToManyField(Room, related_name='roomunit')
class Employee(models.Model):
employee_name = models.CharField()
unit = models.ForeignKey(Unit)
room = models.ForeignKey(Room)
admin.py:
---------
class EmployeeAdmin(admin.ModelAdmin):
list_display('employee_name', 'unit', 'room',)
class RoomAdmin(admin.ModelAdmin):
list_display=('room_no',)
class UnitAdmin(admin.ModelAdmin):
list_display=('unit_name', 'roomno',)
def roomno(self,obj):
r = Room.objects.get(roomunit=obj)
return r
admin.site.register(Employee, EmployeeAdmin)
admin.site.register(Unit, UnitAdmin)
admin.site.register(Room, RoomAdmin)
Sample data were entered for the room and the unit according to the relationship between them.
There is ManyToMany relation between Unit and Room.
Screenshot of Employee add form.
Screenshot of the form
This is what i want to do:
When adding a new employee to the employee add form, when I select the unit name, I want the room_no associated with it to appear automatically
I am trying to create a Django application where each User has one model attached to them ( a list of Plants ) and that model is composed of individual plants. I already know I can have the plants connected to the plant list through a many-to-one relationship using foreign key as shown down below:
class PlantList(models.Model):
plant_list_id = models.AutoField(primary_key=True)
class Plant(models.Model):
plantlist = models.ForeignKey(PlantList, on_delete = models.CASCADE)
name = models.CharField(max_length = 20)
wateringInterval = models.PositiveSmallIntegerField()
However, I want each user to have a plant list attached to them that can be displayed uniquely for each user, according to the plants that they add to their list. How would I make it so that each user has a plant list?
I was trying to have it inside the register form but couldn't figure out how to do it and I wanted each plantlist to have a unique ID so that I can add plants to it easier.
class AddNewPlant(forms.Form):
name = forms.CharField(label='Name',max_length = 20)
wateringInterval = forms.IntegerField(label='Watering Interval')
The thing is, you don't need the model PlantList.
What you should do instead is: set a ForeignKey to the User Model inside the Plant Model, and in that foreign_key set a related_name='plants'.
To access the User Model use:
from django.contrib.auth import get_user_model
code example:
class Plant(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='plants')
name = models.CharField(max_length = 20)
wateringInterval = models.PositiveSmallIntegerField()
Then you can access all user's plants using:
first_user = get_user_model().objects.first().plants
Try this:
class User(models.Model):
plant_list = models.ForeignKey(PlantList, on_delete=models.CASCADE)
this is for connecting plant_list with the user. Also, you need to change the relationship between plant and plant_list, so that users can have the same plants as well like below:
class Plant(models.Model):
plantlist = models.ManyToManyField(PlantList)
that way different users can have the same plants on their plant_list and every user has only one plant_list.
Let's say I have 100 players and 10 teams how can I remove any player from FroreignKey drop-down chooser that is already was chosen for another team?
inside SpielerTeamRelationshipModel I have player = models.ForeignKey(Spieler) and I would like it not to show players who have already been selected for another teams. Is this possible?
class Spieler(models.Model):
name = models.CharField(max_length=128)
vorname = models.CharField(max_length=128)
panels = [
FieldPanel('name', classname="col6"),
FieldPanel('vorname', classname="col6"),
]
class SpielerTeamRelationshipModel(models.Model):
player = models.ForeignKey(Spieler)
in_team_seit = models.DateField()
page = ParentalKey('TeamRooster',
related_name='spieler_in_team')
panels = [
FieldPanel('player', classname="col6"),
FieldPanel('in_team_seit', classname="col6")
]
class TeamRooster(Page):
content_panels = [
FieldPanel('title'),
InlinePanel(
'spieler_in_team', label="Spieler",
panels=None)
]
One Player can be only in one Team. One Team can have one or more players. Very convenient for this is InlinePanel, but every time to choose one player from 100, it's excruciating.
Or maybe I'm not doing the right thing and there's a smarter way to solve this problem?
Strange but no one have mentioned unique_together. It will help you to create unique relations between team and player.
class Player(models.Model):
name = models.CharField(max_length=128)
team = models.ForeignKey(Team, blank=True, null=True)
class Meta:
...
unique_together = ("id", "team")
or sometimes you will need this
class Meta:
...
unique_together = ("name", "team")
Good luck!
Instead of having a player as FK in team
You can solve the problem by having team as FK in Player table
My models are set up as follows:
class Person(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='person_user')
type = models.IntegerField()
class Score(models.Model):
person = models.ForeignKey(Person, related_name='person')
score = models.FloatField(default=0)
I can create Score objects fine and create a relation to the Person. However, the next part is causing some difficulty. I added Score after I had already created the following fields (except for the very last line):
class Applicant_Response(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='user')
interview = models.ForeignKey(Interview, related_name='interviews')
extra_information = models.ForeignKey(ExtraInformation, related_name='extra_information', null=True, blank=True)
score = models.ManyToManyField(Score, related_name='applicant_score', default=1)
I created a Score object that had a score of 0 and a person to use as the default for score (was assigned an ID of 1). However, when I tried accessing the field score in the Applicant_Response, I get profiles.Score.None, which confuses me (profiles is the name of the application).
To my understanding, I am not able to add anything to the manytomany field because it does not exist? Maybe the way I am trying to add Score to Applicant_Response is incorrect?:
try:
applicants = models.Applicant_Response.objects.filter(interview=interviews)
for applicant in applicants:
applicant.score.add(models.Score.objects.get(id=1))
applicant.save()
print applicant.score
except Exception as e: print e
I get the following in stdout: profiles.Score.None
How do I add a Score to the Applicant_Response object?
I find out this:
# You have to Save() first.
applicant.save()
applicant.score.add(models.Score.objects.get(id=1))
# I think it work???
# If not:
sc1 = models.Score.objects.get(id=1)
applicant.save()
applicant.score.add(sc1)
I hope it help you.
I am building a football predictions app whilst learning django and have the following models:
class Team(models.Model):
Name = models.CharField(max_length=30)
class Fixture(models.Model):
HomeTeam = models.ForeignKey(Team, related_name='HomeTeamRef')
AwayTeam = models.ForeignKey(Team, related_name='AwayTeamRef')
HomeTeamScore = models.IntegerField(null=True, blank=True)
AwayTeamScore = models.IntegerField(null=True, blank=True)
Date = models.DateField()
class Player(models.Model):
User = models.ForeignKey(User)
DefaultHomeScore = models.IntegerField()
DefaultAwayScore = models.IntegerField()
class Prediction(models.Model):
Fixture = models.ForeignKey(Fixture)
HomeTeamScore = models.IntegerField()
AwayTeamScore = models.IntegerField()
Date = models.DateTimeField()
Player = models.ForeignKey(Player)
I have many fixture objects populated and have been using model formsets based on the Prediction model to render a view which allows the user to enter scores.
The problem is that they must choose which fixture the prediction relates to. I would like to pre-populate this so they get a list of fixtures and just enter the hometeamscore and awayteamscore. This involves pre-poulating the Prediction.Fixture field and Prediction.Player field but I am unsure on how to go about this?
Any help is much appreciated.
Edit: The problems seems to be how to pass multiple instances of Fixture into a Prediction model formset, I have seen examples of passing one but would like to do this all in one go.
I also would like the user to be able to make one Prediction per Fixture.
I think this is what you are looking for:
https://docs.djangoproject.com/en/1.7/topics/forms/formsets/#using-initial-data-with-a-formset
Your code would look something like this:
initial_data = []
for fixture in fixtures:
initial_data.append({'Player':player,'Fixture':fixture})
formset = MyPredictionFormset(initial=initial_data)
P.S. Not to be pedantic, but your field names are not PEP 8 compliant. They should be lowercase with underscores, but it's your call. (http://www.python.org/dev/peps/pep-0008/)