Friday, July 6, 2012

Re: ForeignKey problem

On 6-7-2012 15:17, Soviet wrote:

> Lets try LEGO pieces. I have a LEGO set that has many pieces (ManyToMany).
> But I have 4 wheels and 1 brick in that set. The 'brick' can be added with
> no problem, but how do I save the information that there's 4 'wheel'
> objects and not only one?

You don't. You get all wheel objects and count them. However, I think
the through argument is best explained with your original question, when
you asked:
"Say I want to add list of all Teams my Players played for."

This does not change the player model, nor the team model. What you're
asking for here, is a new model "player history", which is defines the
many-to-many:

class Team(models.Model) :
name = models.CharField(max_length=64)

class Player(models.Model) :
name = models.CharField(max_length=64)
playing_for = models.ForeignKey(Team, related_name='players')
history = models.ManyToManyField(Team, related_name='player_histories',
through='PlayerHistory') #quoted!

class PlayerHistory(models.Model) :
team = models.ForeignKey(Team)
player = models.ForeignKey(Player)
started = models.DateField()
ended = models.DateField()


--
Melvyn Sopacua


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment