Monday, January 9, 2012

How to make a single 'special' m2m relationship?

Hello, I'm new to Django (and to MVC, in fact) but I'm liking it a
lot.

I followed the beginners tutorial, and I'm now trying to put together
a very simple "articles" app, which has these models so far:

class Tag(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name

class Article(models.Model):
title = models.CharField('Article title', max_length=40)
pub_date = models.DateTimeField('Publish date')
ready_to_publish = models.BooleanField()
tags = models.ManyToManyField(Tag)
def __unicode__(self):
return self.short_title

Here's my question... I want articles to have multiple tags, which is
why I've used "models.ManyToManyField". But when I design the HTML
page, I want one 'primary' tag to appear at the top of the article
post, by the headline, and then the rest of the tags to appear at the
bottom. So I need a way of specifying a 'primary tag' for each
article. In other words, I might want to give the article the tags
"art", "color", and "painting", but I want to specify that "painting"
is the primary tag for this article.

I tried adding the following property to the Article class:

primary_tag = models.ForeignKey(Tag)

...but then when I run syncdb, I get the following error message:

Error: One or more models did not validate:
articles.article: Accessor for field 'primary_tag' clashes with
related m2m field 'Tag.article_set'. Add a related_name argument to
the definition for 'primary_tag'.
articles.article: Accessor for m2m field 'tags' clashes with related
field 'Tag.article_set'. Add a related_name argument to the definition
for 'tags'.

I don't really understand the error message. Am I approaching this the
wrong way?

If I was doing this manually with SQL, I would probably make a table
especially for the m2m relationship, called "articles_tags", and this
table would have ariticle_ids linked to tag_ids, and then I'd add a
boolean field to this table called something like "is_primary".

What is the correct way to approach this with Django?

Thanks,
Callum

--
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.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate