Many-to-Many and Many-to-one relation
I would really appreciate it if someone can validate the many-to-many and Many-to-one relations in my code:
The project:
1- There are different "category" (ex:'world news' 'europe' 'business' 'sports'); these "category" will be predefined and should change a lot once (add new / delete an entry)
2- "news" are associated to one "category".
3- "User" can register to as many "category" as he want (the goal being to develop a site that displays "news" that falls in the "category" a "user" register to.
4- A User have the option to remove a news from his "news feed". When this happens, the "discarded" boolean field is set to True (see the "news" class).
class Category(models.Model):
category = models.CharField(max_length=50)
class News(models.Model):
question = models.CharField(max_length=100)
pub_date = models.DateTimeField()
discarded = models.BooleanField()
category = models.ForeignKey(Category)
class User(models.Model):
name = models.CharField(max_length=50)
subscribed_category = models.ManyToManyField(Category)
Question:
I would really appreciate it if you can verify that the foreignKey and manytomany fields are c开发者_开发技巧orrectly implemented in the code. Any Improvement will be more than welcome :)
No, this isn't quite right. The problem is with the discarded
attribute. If I understand correctly, a News
object is an item in a specific Category, so it has no relation with a particular user. If you set discarded
on the News object, it will be set for all users.
However it's not entirely obvious how to model this, as there is (correctly) no relationship between User and News. You will need something like an additional ManyToMany between those two tables, to hold the discarded items:
class User(models.Model):
...
discarded_items = models.ManyToManyField('News')
So to get the current list of news for each user, you would just check that the item is not in user.discarded_items
.
What you wrote is perfectly fine and it will work. However, the best way to do such things is to define we model, for example (in your case):
class UsersInCategories(models.Model):
user = models.ForeignKey(User)
category = models.ForeignKey(Category)
The reason is because you may want to add some additional data later, like for example the datetime of subscribing or something else. Note that when you use ManyToManyField, then django does this behind the scene (some additional table should appear in your database with such structure, although i didn't test it yet). So if you don't need additional data, then it's ok.
精彩评论