I have a specialized User class that inherits from django.contrib.auth.models.User. Now, this User class will have tags associated with it, for example: Blogger, French Cuisine Cook, Python Programmer.
Ideally, what I want to do, is have each of these traits backed up by something that they have done, ideally a PortfolioItem. So, a User will have a set of tags, and these tags, and the relationship with each of these tags is going to be understood through these PortfolioItems. How would one achieve something like this using the django ORM?
Please note, that the tags are generic, however, the portfolios behind each of these tags are unique to every user.
How would one go about doing, this using the through variable in django ORMs.
UPDATE
I've tried simple adding PortfolioItem as the through variable, but in that case you will need to create a unique tag each time you want to add a list of portfolio item. The thing is I want tags to be generic.
Related
I'm trying to create a kind of "subfield" for a CharField in django, but I'm not sure (a) if it is possible at all and (b) how to succeed if it is indeed possible.
Let's say I want a model for Tools. They would have a, e.g., a field for long_name, short_name, maybe a ForeignKey for realizing different departments. One of these tools I'd like to be a Link, the said "subfield" being a URLField with the href to the webpage.
Now, I can create multiple link entries with the associated URL, but I'd rather have only one tool called "Link" with the changing URL attached. Is this a case for ForeignKey as well? Does it make sense to have a model with only one field (well, two if you count the pkid) in it?
Or am I on a completely lost path here?
If I've understood you correctly, you want to have a number of links that can be attached to a Tool model, so instead of just having a single URLField you would have a Many-to-One relation with a Link model:
class ToolLink(models.Model):
url = models.URLField(...
class Tool(models.Model):
links = models.ForeignKey(ToolLink, ...
The problem is that you only want one particular tool to be able to hold links. Your options are to create a 'Tool' base model that then has multiple different types of tool, like 'StandardTool', 'LinkTool', etc. or to setup some logic that monitors whether the Tool has links or not (or if another tool already has links) and whether creating links is acceptable.
This is more of a conceptual/engineering question than an actual programming question, but I keep going back and forth between what is the "right" thing to do here. For quick background, I am still a bit of a noob at python/django and don't have a ton of experience working with classes.
The program I'm trying to develop is an inventory management app.
There are multiple products but lets simplify and say one is shoes and one is clothing. Both products share some attributes (UPC, size, color, etc), but also have some unique attributes (shoe_width, clothing_type) as well.
Additionally, it seems like I should have a separate Product class (unique product attributes UPC, size shoe_width, clothing_type) and InventoryItem class (attributes unique to each piece of inventory such as price paid or condition) that inherits its corresponding Product class attributes.
EDIT2: clothing_type is unique to clothing, but shoe_width should be unique to the actual shoe InventoryItem and not the shoe Product. This sort of complicates the question, as now I'm thinking I'll need not only seperate Clothing and Shoe classes, but also ClothingInventoryItem & ShoeInventoryItem classes to deal with unique fields down at the inventory level.
Conceptually, I am trying to build this multi-purpose. Users should be able to view product information (not inventory related) and add products and inventory items via django admin or via spreeadsheet upload (spreadsheet hooks already built.)
So to the actual question, what is the correct way to implement the individual classes and what are some of the problems I may run into or drawbacks to doing so? I'm having a problem visualizing how this would work.
Should I:
A)
Have a ProductType field (make two initial entries of "Shoe" &
"Clothing")
Have separate "Shoe" and "Clothing" classes which inherit ProductType
via models.ForeignKey(ProductType). They would then have their own
unique fields regardless if they share some fields.
Have an InventoryItem class that then inherits Shoe or Clothing via ForeignKey.
The only limitation I can see is that the admin users would not be able to add new ProductType without me having to write a new class for that new ProductType (which is totally fine.)
Thanks in advance.
Edit: When I was initially typing this, the alternative scenario would be to do these relationships correctly via python nested classes and then feed the info into the django model classes...but this seems redundant and unnecessary.
I have two simple models Article and Topic, and as you can guess every article can belong to one or more topics.
The main functionality of this little app is to show all articles for a specific topic that the user selected.
What model should have the ManyToManyField? For my use case, I would say it makes sense to put it in the Topic model. However, if I do that I would always need 2 queries if I add a new article (1 on the Article model, and 1 on the Topic model to make the relationship).
I found this generic rule, but it's not helping me much in this situation.
"Generally, ManyToManyField instances should go in the object that’s going to be edited on a form. In the above example, toppings is in Pizza (Article) (rather than Topping (Topics) having a pizzas (article) ManyToManyField ) because it’s more natural to think about a pizza (article) having toppings (topics) than a topping (topic) being on multiple pizzas (articles). The way it’s set up above, the Pizza (Article) form would let users select the toppings (topics)." -docs
Just quoting because it's interesting the doc's emphasis is more on the UI than the ORM.
Also you're probably already doing this by just in case, I like to interact with my app via the shell to try out different queries in situations like this.
I would say you work things top -> down. Which is the top level object should have the relation description (ManyToManyField).
Why? Look at things from user interface point of view. You present the list of TOPICS or FORUMS before you go into articles and threads. RESTful urls also follow this logic as urls usually have TOPIC/topic_id/post/post_id/ not the other way around. For this reason I think it makes sense to add ManyToManyField to Topic not post, to Forum not article/thread.
You also get to use cool django stuff like
Topic.objects.get(id = topic_id).select_related()
My 2 cents anyway.
Edit1
I do not follow this advice all the time. For example:
There is Person and there is Group, which is meant to identify bunch of Persons. Where to put manytomanyfield there? Django, has put the manytomany connection to its Person (django.contrib.auth.models class User via mixin) not Group. I have done it the other way around in one case. Why? Because i wanted users to be able to add Person's to Group in Group's view not Person's view. And i did not want to do something like looping through bunch of persons to add single group to each of them. Looking back at this i still do not know if it was bad or good decision because it would have brought me problems either way :P
So i guess i want to say that you should evaluate each case separately and always think ahead about what you want to do with each class and object in the future.
/Edit1
I wonder if you could help me.
I have a list of data that will be displayed on one page. There is a simple search box, a list of categories and a list of tags that can all be used to filter the list of data. I'm trying to built it from the ground up (so it doesn't require JavaScript) but eventually it will submit the search criteria and return back a new list using Ajax.
So I have a list of categories in my database ('large', 'small', etc), and I have a list of tags in my database ('wooden', 'brass'). Tags are used to filter down more of what's in the categories. I then have a search box. Ideally, I want the user to effectively tick which categories they want, tick what tags they want and possibly put a search for keywords, and then submit all of that data so it can be queried and a new list of the filtered data can be returned.
I'm not a Django expert, and I'm stuck on how and where to do this... What is the Django way of spitting out the categories as a checkbox list, the tags as a checkbox list and the search box with a submit button... Which when submitted, I can take all that data and do the necessary queries on the database? I don't quite understand how I'd do this... I've been looking at the Django Docs and the Django Book for a few days and the way I'm doing things doesn't seem to be listed.
Please, any help at all would be fantastic.
spitting out the categories as a checkbox list,
the tags as a checkbox list and the
search box with a submit button...
This is a <form> in your HTML page. It probably doesn't match anything in the Django model very well. It's a unique form built more-or-less manually.
I can take all that data and do the necessary queries on the database?
That's a view function.
You'll probably have something like this.
objects= SomeModel.objects
if request.GET ... has categories ...
objects = objects.filter( ... categories ... )
if request.GET ... has tags ...
objects = objects.filter( ... tags ... )
if request.GET ... has search ...
objects = objects.filter( something__contains( search ) )
return render_to_response( ... etc. ... )
the way I'm doing things doesn't seem to be listed.
You're beyond the tutorial here.
What to do?
Do the ENTIRE tutorial. All the way through. Every step. It doesn't seem like it solves your problem, but you MUST do the ENTIRE tutorial.
Design your model. You didn't mention the model in the question. It's the absolutely most important and fundamental thing.
Create the default admin interface for that model. Get the default admin interface to work and do the kinds of things you'd like to do. It has great search, category and tag filtering.
In order to get the default admin to work, you'll need to design fairly sophisticated model and form features. You'll probably have to add method functions to your model as well as choice items and other goodness.
AFTER you have the admin page pretty close to what you want, you can write you own customized view.
each single checkbox has a different name ('category_option_1', 'category_option_2', etc.) ... How do I read these? I can't just put request.POST['category_option_n']?
Really? Why didn't your question say that?
Are you asking about this?
for k in range(1024):
name = 'category_option_{0}'.format(k)
# Use request.POST.get(name,None) to build a `Q` object
I'm still not sure this is the correct way to go about this, maybe not, but I'll ask anyway. I'd like to re-write wordpress (justification: because I can) albeit more simply myself in Django and I'm looking to be able to configure elements in different ways on the page. So for example I might have:
Blog models
A site update message model
A latest comments model.
Now, for each page on the site I want the user to be able to choose the order of and any items that go on it. In my thought process, this would work something like:
class Page(models.Model)
Slug = models.CharField(max_length=100)
class PageItem(models.Model)
Page = models.ForeignKey(Page)
ItemType = models.CharField(max_length=100) # tells me which model to display
InstanceNum = models.IntegerField() # tells me which instance of which model...
Then, ideally, my template would loop through all the PageItems in a page which is easy enough to do.
But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to pull different item types back in different orders and display them using the appropriate templates. Now, I thought one way to do this would be to, in views.py, to loop through all of the objects and call the appropriate view function, return a bit of html as a string and then pipe that into the resultant template.
My question is - is this the best way to go about doing things? If so, how do I do it? If not, which way should I be going? I'm pretty new to Django so I'm still learning what it can and can't do, so please bear with me. I've checked SO for dupes and don't think this has been asked before...
I've also looked at Django-cms to see if that helps, but I couldn't get to grips with it.
Any suggestions?
First, some puzzelement.
InstanceNum = models.IntegerField() # all models have primary keys.
In Django, all model are assigned an integer primary key.
The comment doesn't make sense, since you don't need to add a primary key like this. The PageItem already has a primary key.
Also, please use lower case letters for attributes. Only Use Upper Case for Class Names. Please.
"But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to
pull different item types back in
different orders and display them
using the appropriate templates"
Different types usually means different models. Rather than a vague "PageItem", you probably want to have "Site Update" and "Blog Post" as separate models.
You can then iterate through these various objects and display them in the template.
You can easily have your various Models defined with a method to return HTML information. You don't (generally) want to return fully-baked HTML. But CSS ID or Class information is sometimes helpful.
class SiteUpdate( models.Model ):
page = models.ForeignKey(Page)
item_text = models.CharField(max_length=100)
item_css_class = models.CharField(max_length=64)
Now you can generate this into the template with a simple <div class="{{item.item_css_class}}">{{item.item_text}}</div> and use CSS to handle the formatting details that distinguish site update as opposed to a blog post.
The include template tag can take a variable containing the template to include, so you could loop through a sequence containing the various sub-templates and include them in turn, maybe using a dict to map friendly names to template filenames.