Which model should be higher? - django

Which model should be higher? I still have a error.
class Post(models.Model):
blog = models.ForeignKey(Blog)
class Blog(models.Model):
post = models.ManyToManyField(Post,blank=True,null=True)

Essentially, you don't need the foreign key from Post -> Blog. See the docs. ManyToMany give you the reverse direction as part of their default behaviour.
Edit (as per #Tony Blundell), you can specify models via a string for foreign keys in cases of order-of-definition issues. However, in this case this (I assume) this isn't what you are trying to do. In your case, scrap the ForeignKey under Post, and then you can make use of the reverse behaviour of M2M to represent that relationship.
Also I'd check out the docs, as they are really good for the Django project and cover all of the basics. The Tutorial, if you haven't done it yet, is very useful.

Related

How to create an associative entity with extra fields in django

I am facing the following problem.
I have to entities,Proposal and User, a user can vote up or down several proposals and a proposal can have several votes from several users.
This relation between Proposal and User is Many to Many, the thing is that here I want to add an extra field to indicate if the Vote is positive or negative.
Is there are a way to do this in Django using ManyToManyField?, or the only way to do this is creating the model entity of Vote by hand like this:
class Vote(models.Model):
user = models.ForeignKey(User,related_name='voter',null=False)
proposal = models.ForeignKey(Proposal,related_name='vote_to',null=False)
opinion = models.BooleanField(blank=False,null=False)
And in case I have to do it by hand, how I can do for saying to Django that the primary key is the composition of the others Foreign keys
Creating a separate model Vote is a better way to do it, because a vote is specific to a particular proposal for a particular user, so it can't be directly linked to the Proposal model or to the User model.
See this article regarding mutiple column primary keys support in Django, and also this answer.

Tracking a reverse relationship for a foreignkey in django-reversion

I'm trying to figure out how how to track changes for a foreignkey relationship in Django using Django-reversion.
In short, I am trying to model a Codelist, which contains Codes which only belong to one Codelist. This can be modelled using a foreign key like so:
class CodeList(models.Model):
name = models.CharField(max_length=100)
class Code(models.Model):
value = models.PositiveIntegerField(max_length=100)
meaning = models.CharField(max_length=100)
codelist = models.ForeignKey(CodeList,related_name="codes")
Additionally, the only way to edit a code is by using an inline form in the admin site accessed via its codelist. For all intents and purposes, codes belong to codelists as they should...
Except when it comes to reversion.
I'm using the reversion.middleware.RevisionMiddleware to track all editing changes, as there are some non-admin forms for editing codes.
What I'd like is when I see the history of a codelist, it should changes to the codes as well, but I can't figure that out in the Django-reversion API. The issue is that the API covers tracking the code, and seeing changes to the codelist, not the other way around by following the reversed relationship.
Is anyone aware of how this might be done?
Its not well documented Its very well documented, I just couldn't find it, but you can just add the inverse relationship as the field to follow like so:
reversion.register(CodeList, follow=["codes"])

Are Sortable inlines on Grappelli applicable for M2M fields?

I can't seem to get the sortable inlines feature (in grappelli) work for me.
I'm starting to wonder if the feature is not supported for ManyToManyFields or if I am not getting it right.
Also, is there a sample code out there so I can see and learn? I already followed the method described here.
M2M Fields didn't work for me. But, turns out there's a work-around for this.
I created a through model for a ManyToManyField and added order in that through model. Remember, the through model uses ForeignKey fields. So, the case essentially becomes that of managing a couple of one-to-many relationships.
Implementing sortable inlines is now as easy as following Grappelli's documentation.

Can I make Django admin reflect a hierarchy of models?

Assume a Django application with a few models connected by one-to-many relationships:
class Blog(models.Model):
...
class Post(models.Model):
blog = models.ForeignKey(Blog)
...
class Comment(models.Model):
post = models.ForeignKey(Post)
...
Conceptually, they form a hierarchy, a tree-like structure. I want the Django admin to reflect that. In particular:
in a changelist of posts, every post should have a link to the changelist of corresponding comments;
similarly, a post’s edit page should link to the changelist of comments from the top-right buttons area;
when I open that list of related comments, it needs to reflect the relationship in the breadcrumbs (something like: Posts › “Hello world” › Comments) and, ideally, also in the URL (post/123/comment/).
This should of course also apply to the other levels of the hierarchy.
Number 1 is pretty easy with a custom list_display entry and using the ?post__id= query to the comments changelist. But this is little more than a hack. Generally Django assumes my three models to be independent, top-level entities.
Is there a straightforward way to accomplish this? I guess I could override a bunch of templates and AdminModel methods, but perhaps there is a better solution for what seems like a common situation?
Are you sure you are not just looking at Django Admin Inline Models ?
There is no way that an automated admin will pick up your relationships, because in an RDBS there can be any number of foreign keys / one to one / many to many relations, and Django does not have a customized hierarchical behavior built in.
You can indeed edit the breadcrumb customizing an admin template if you want.
For relations you might also be interested into django MPTT that allows to make hierarchical model instances. Also see this question: Creating efficient database queries for hierarchical models (django) in that respect.
How is this a common situation? Consider the fact a model can have a virtually unlimited number of foreign key relationships, let alone visa versa. How would the admin 'know' how to represent this data the way a user requires without customizing things?
One would suggest you are used to work with content management systems rather than webframeworks (no pun intended). It's important to notice Django isn't a cms, but a webframework you can built on top of as you see fit. In a nutshell: 'Django is rather clueless and unaware of contextual requirements'.
Although the admin is quite a beast out-of-the-box, it can be hard to customize. There have been quite some discussions whether it should even be part of core. I can only suggest, if customizing things tends to get hacky, you should probably write your own 'admin', it's not that hard.

Customize Django comments framework so that the comment does not have to be unique

I'm customizing the comments model per the Django documentation.
In my specific use case, however, comments are allowed to be blank. The trouble I get into then is that the Comment model is setup with an unique_together:
unique_together = [('user', 'comment', 'flag')]
Any ideas on how I could go about overriding this?
(...or did I start off on the wrong track with using the Comments framework altogether? :)
Doesn't look like the Comment model has a unique constraint.
Code for models.py for contrib.comments.
It looks like the CommentFlag model has the uniqueness constraint which shouldn't effect you having blank comments.
Your problem must lie elsewhere.
I'm not very familiar with the comments app but here are some ideas you can look at to get around your problem.
Warning I haven't used either of these methods on the comments app so I'm not sure if using these will break any downstream functions of the comments framework. Be sure to look into/test if you decide to use either of these.
That being said, I can think of 2 ways you can approach this.
Override the unique together:
class NonUniqueComment(Comment):
class Meta(Comment.Meta):
unique_together = []
Make the comments field store Null instead of empty string in the db.