Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
bitprophet
Jul 22, 2004
Taco Defender

Wulfeh posted:

I was under the impression that class Meta ordering was "bad", something to do with inheritance, I forget. It was something mentioned by David Cramer at djangocon. Does anyone remember the exact reason why?

IIRC one of the forms of inheritance has to stomp on the Meta inner class and/or can have odd behavior with it. I don't recall anything about it being bad per se, however, and I can't possibly imagine it would be a reason not to use Meta.ordering at all. Do you remember if it was on his slides?

Adbot
ADBOT LOVES YOU

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

bitprophet posted:

I know that's probably a lot to absorb for a newbie, but if you read up just a little bit on Python importing and modules, it should make sense.

Thanks I got it working, just had to fight with the order in which the imports needed to be in.

Those 200+ lines had no functions in them whatsoever, so I was expecting it to blow up into the 800 range with very few things in common.

Janitor Prime fucked around with this message at 23:18 on Nov 6, 2008

king_kilr
May 25, 2007

Wulfeh posted:

I was under the impression that class Meta ordering was "bad", something to do with inheritance, I forget. It was something mentioned by David Cramer at djangocon. Does anyone remember the exact reason why?

If I recall correctly he was running into something where it was lreading to ordering a huge dataset where it wasn't necessary.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
I watched the Djangocon vid again, and he mentioned that when you start using joins across several tables with Meta Ordering, it will do ordering on every table where Meta ordering was specified. So for large datasets, it will be ordering itself several times over, which you probably don't want it doing.

Wulfeh fucked around with this message at 16:19 on Nov 7, 2008

Mashi
Aug 15, 2005

Just wanted you to know your dinner's cold and the children all agree you're a shitheel!
What's the best way to create an url in the format "/yyyy/mmm/dd/slug" given an url name and a model? To elaborate:

code:

# url in urls.py:
url(r'post/(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[\-\d\w]+)/$',
    'mysite.blog.views.post', name="view_post")

# somewhere else:
>>> from django.core.urlresolvers import reverse
>>> from mysite.models import Post
>>> p = Post.objects.all()[0]
>>> url = reverse("view_post", args=[?????????]) # this is the bit i am unsure of
>>> print url
"/post/2008/nov/12/this-is-a-slug"
Also, is reverse() slow? Are there better alternatives which still have the loose coupling benefit?

Mashi fucked around with this message at 22:11 on Nov 13, 2008

bitprophet
Jul 22, 2004
Taco Defender

Mashi posted:

What's the best way to create an url in the format "/yyyy/mmm/dd/slug" given an url name and a model?

Think of it from the Python method call perspective; when you set up your URL (the one in your example) you had the regex capture some named arguments: 'year', 'month', 'day' and 'slug'. Thus, those are keyword arguments (kwargs), and so your view function is called like post(year='2008', month='5', day='6', slug='my-slug-lol').

If you had captured parts of the regex without naming them, they'd be regular arguments (args) instead of keyword ones.

Finally, this args/kwargs dichotomy is then applied to the reverse function, so you can recreate (backwards) a URL for a given view call. The args argument to reverse is a list of the args, if any, and the kwargs argument is a dict of kwargs, again if any.

So, what you want for your example is reverse('view_post', kwargs={'year': '2008', 'month': 'nov', 'day': '12', 'slug': 'this-is-a-slug'}).

This way of passing around a method's args and kwargs for deconstruction/reconstruction is a typical Python idiom, so you should definitely get comfortable with it. (It shows up a lot with the */** stuff for defining and/or calling a method with a list of args/dict of kwargs -- which is actually what's being done with what you're giving reverse()).

Mashi
Aug 15, 2005

Just wanted you to know your dinner's cold and the children all agree you're a shitheel!
Ok, thanks :). When I first came across reverse() I was confused because it seemed like incredible magic so I was sorta wondering if Django would guess the output that I wanted and take care of it for me.

bitprophet
Jul 22, 2004
Taco Defender
There's no magic involved because you're using named URLs (the name='foo' in the URLconf), and that provides an unambiguous 'key' to look up. Then the args/kwargs is simply there for you to construct a specific URL -- for the one in your example, you can't really "go to" or "have" that particular URL without the arguments (the date stuff and the slug).

I can't recall off the top of my head if there's another method that exists or used to exist, which would do magic by trying to reverse-engineer a URL, but that's where any magic would be. The named URLs -- which are a great idea and should IMHO always be used -- are where it's at. No ambiguity, no magic, and no speed hit that I'm aware of :) (given that it's likely using a dict in the background, which is constant speed access!)

king_kilr
May 25, 2007
FYI, reverse often appears slow, but it's cached, so it's not a big performance issue(compared to all the other things that can be slow in a request).

hitze
Aug 28, 2007
Give me a dollar. No, the twenty. This is gonna blow your mind...

I've been trying to get this nested forloop to work for the last two days and I can't seem to get it working right. I've got three models: Artist, Album, Song. The artist model is just information by itself, and the album model has a ForeignKey linking it to an artist, and the song model has a ForeignKey linking it to an album.

I've tried this as my view:
code:
def artist_page(request, artist_slug):
	artist = get_object_or_404(Artist, Slug=artist_slug)
	albums = Album.objects.filter(Artist=artist.id)
	songs  = Song.objects.filter(Album=albums.id)
	return render_to_response('main/artist_page.html',
		{
			'artist_results': artist,
			 'album_results': albums,
			  'song_results': songs,
		},
		context_instance = RequestContext(request)
		)
Coupled with this template:
code:
    {% for Album in album_results %}
	<div>
		<h3>{{ Album.Name }}</h3>
			<ol>
				{% for Song in song_results %}
				<li>{{ Song.Name }}</li>
				{% endfor %}
			</ol>
	</div>
    {% endfor %}
I can't seem to get the songs to list or get called, so i'm hoping i'm missing something that should be really obvious. Any help would be appreciated :)

bitprophet
Jul 22, 2004
Taco Defender
Well, first off, Python is case sensitive, so are your field names really capitalized like that (Name and so forth)? If they are, then I don't see anything obviously wrong with your code -- but they should not be capitalized, as it's nonstandard Python naming (generally only class names get capitalized/camelcased, and everything else is lowercased with underscores, i.e. my_variable). Following a language's style is always a good idea as it makes collaboration with (or assistance from :)) other coders, much easier.

Can you paste your model file? It will answer my above question, and the view and template are only two parts of the puzzle -- troubleshooting is always more difficult without the entire picture.

Finally, while I doubt this is your problem, keep in mind that the default string representation of Python objects happens to be HTML-tag-like (<MyObj foo>) so if you were ever to try and do {{ some_object }} it would look, in-browser, as if nothing was there. So a good tip is to always View Source when you don't see an expected string, in case this is what's going on.

However, you seem to be doing {{ object.attribute }} which usually doesn't have this problem (as the attribute values are typically simple values like strings and integers) so that's probably not what's going on -- but the phenomenon is good to keep in mind regardless :)

hitze
Aug 28, 2007
Give me a dollar. No, the twenty. This is gonna blow your mind...

bitprophet posted:

Well, first off, Python is case sensitive, so are your field names really capitalized like that (Name and so forth)? If they are, then I don't see anything obviously wrong with your code -- but they should not be capitalized, as it's nonstandard Python naming (generally only class names get capitalized/camelcased, and everything else is lowercased with underscores, i.e. my_variable). Following a language's style is always a good idea as it makes collaboration with (or assistance from :)) other coders, much easier.

Can you paste your model file? It will answer my above question, and the view and template are only two parts of the puzzle -- troubleshooting is always more difficult without the entire picture.

Finally, while I doubt this is your problem, keep in mind that the default string representation of Python objects happens to be HTML-tag-like (<MyObj foo>) so if you were ever to try and do {{ some_object }} it would look, in-browser, as if nothing was there. So a good tip is to always View Source when you don't see an expected string, in case this is what's going on.

However, you seem to be doing {{ object.attribute }} which usually doesn't have this problem (as the attribute values are typically simple values like strings and integers) so that's probably not what's going on -- but the phenomenon is good to keep in mind regardless :)
Yeah the fields are capitalized, don't really know why I started doing that. :downs:

The Model:
code:
class Artist(models.Model):
	Name  = models.CharField(max_length=255)
	Slug  = models.CharField(max_length=255)
	Bio   = models.TextField()
	Photo = models.ImageField(upload_to="G:\web\htdocs\lyrics")
		
	def __unicode__(self):
		return self.Name
		
class Album(models.Model):
	Artist = models.ForeignKey(Artist)
	Name   = models.CharField(max_length=255)
	Slug   = models.CharField(max_length=255)
	Date   = models.DateField()
	Art    = models.ImageField(upload_to="G:\web\htdocs\lyrics")
	
	def __unicode__(self):
		return self.Name

class Song(models.Model):
	Album  = models.ForeignKey(Album)
	Name   = models.CharField(max_length=255)
	Slug   = models.CharField(max_length=255)
	Lyrics = models.TextField()
	
	def __unicode__(self):
		return self.Name
		
The template does give me the first bit of data(The album name), but the song list doesn't get rendered.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

hitze posted:

code:
				{% for Song in song_results %}
I can't seem to get the songs to list or get called, so i'm hoping i'm missing something that should be really obvious. Any help would be appreciated :)

try
code:
				{% for Song in Album.song_set %}

bitprophet
Jul 22, 2004
Taco Defender

deimos posted:

try
code:
				{% for Song in Album.song_set %}

Aha, that's right! I hadn't noticed the details of the assignments in the view.

hitze, your line here:
code:
songs = Song.objects.filter(Album=albums.id)
is incorrect -- 'albums' in that context is a list of albums, so how could you possibly get its 'id'? :) that would only work on a single Album object.

Instead of that approach, Deimos' example is correct: you need to make sure you understand the OO nature of Python and Django's models, in that to get to "an album's songs", you generally want to be asking the album object for its songs, not trying to get that query out of the database directly with Song.objects.filter as you did above.

If you (re?)read the Django model docs, you'll see that when you declare the ForeignKey from Song => Album, it adds the reverse relationship to Album objects, allowing them to look at 'song_set', which is a manager like Song.objects, except it only returns songs related to that one album, so my_album.song_set.all() returns the entire album's worth of songs.

Thus, a ForeignKey adds the forward relationship -- 'my_song.album' -- and the reverse -- 'my_album.song_set', and you want to be using those to "navigate" the object hierarchy, instead of doing it manually.

ijustam
Jun 20, 2005

By the way, Django has a slug field :)

http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

bitprophet posted:

:words:

Thanks for actually verbalizing my post. I didn't have time to write a full answer when I posted that.

hitze
Aug 28, 2007
Give me a dollar. No, the twenty. This is gonna blow your mind...

Well after rereading the docs for models and page 3 of the tutorial (for the upteenth time) I came up with this:
code:
def artist_page(request, artist_slug):
	artist = get_object_or_404(Artist, Slug=artist_slug)
	albums = Album.objects.filter(Artist=artist.id)
	[b]s      = Album.objects.get()
	songs  = s.album_set.all()[/b]
	return render_to_response('main/artist_page.html',
		{
			'artist_results': artist,
			 'album_results': albums,
			 'song_results': songs,
		},
		context_instance = RequestContext(request)
		)
I get this error when there are more than one albums in the db.
code:
MultipleObjectsReturned at /artist/led-zeppelin/
get() returned more than one Album -- it returned 2! Lookup parameters were {}
And this when theres only one album total.
code:
AttributeError at /artist/led-zeppelin/
'Album' object has no attribute 'album_set'
It might be just me burned out for the day, but this is totally stumping me :suicide:

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

hitze posted:

Well after rereading the docs for models and page 3 of the tutorial (for the upteenth time) I came up with this:

Gah, go back and re-read the tutorial and documentation, specifically this page.

1. Why do you insist on setting the albums and songs to a variable.
2. Why are you using get() when stuff might return more than one value? You use get to get a single instance.


For #1 you do not need to be declaring all those variables on your view.

Try this as your view:
code:
def artist_page(request, artist_slug):
	artist = get_object_or_404(Artist, Slug=artist_slug)
	return render_to_response('main/artist_page.html',
		{
			'artist_results': artist,
		},
		context_instance = RequestContext(request)
		)
And this for your template:
code:
{% for Album in artist_results.album_set %} 
	{{ Album.Name }}
	{% for Song in Album.song_set %} 
		{{ Song.Name }}
	{% endfor %}
{% endfor %}

quote:

code:
AttributeError at /artist/led-zeppelin/
'Album' object has no attribute 'album_set'

That's because Album indeed does not have an album_set; artist has an album_set and each album in the album_set has a song_set.

deimos fucked around with this message at 17:31 on Nov 16, 2008

hitze
Aug 28, 2007
Give me a dollar. No, the twenty. This is gonna blow your mind...

deimos posted:

Gah, go back and re-read the tutorial and documentation, specifically this page.

1. Why do you insist on setting the albums and songs to a variable.
2. Why are you using get() when stuff might return more than one value? You use get to get a single instance.


For #1 you do not need to be declaring all those variables on your view.

Try this as your view:
code:
def artist_page(request, artist_slug):
	artist = get_object_or_404(Artist, Slug=artist_slug)
	return render_to_response('main/artist_page.html',
		{
			'artist_results': artist,
		},
		context_instance = RequestContext(request)
		)
And this for your template:
code:
{% for Album in artist_results.album_set %} 
	{{ Album.Name }}
	{% for Song in Album.song_set %} 
		{{ Song.Name }}
	{% endfor %}
{% endfor %}
That's because Album indeed does not have an album_set; artist has an album_set and each album in the album_set has a song_set.
I reread that page, and tried your example and it threw an error of Caught an exception while rendering: 'RelatedManager' object is not iterable
.
So I searched around and found people put .all at the end of the _set, and now it works!
code:
{% for Album in artist_results.album_set.all %} 
	{{ Album.Name }}
	{% for Song in Album.song_set.all %} 
		{{ Song.Name }}
	{% endfor %}
{% endfor %}
You two are scholars and gentlemen, thanks for the help :)

Digital Spaghetti
Jul 8, 2007
I never gave a reach-around to a spider monkey while reciting the Pledge of Alligence.
The last Django application I worked on was in 0.96 and I'm trying to
get used to the new stuff in there.

I've been following the docs here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id2
trying to use the formset_factory on some forms.

I have a Contact model, and associated through a FK it has several
ContactNumber and ContactEmail instances. I've used ModelForm to
create the forms and it works successfully if I just have one instance
of the number and email, but when I try to create a formset for it, I
get this problem:

'ContactNumberFormFormSet' object has no attribute 'save'

But as far as I can see, I've followed the docs correctly??

I've pasted the code for my model, form and view below:

Contact,ContactNumber,ContactEmail models: http://paste.ifies.org/158
Forms: http://paste.ifies.org/161
View: http://paste.ifies.org/160

Any help on this would be appreciated

king_kilr
May 25, 2007
I think you mean to be using model formset factory, instead of formset factory.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Guys I need help with the media urls, I'm pulling my hair out :(.

# Absolute path to the directory that holds media.
MEDIA_ROOT = 'C:/Dungeons/dnd/media'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
MEDIA_URL = 'http://media.localhost:8000/'


I have an image called paladin.jpg in C:\Dungeons\dnd\media\img\

and in my template I have <img src='http://media.localhost:8000/img/paladin.jpg'></img>

Why won't it work :cry:. I guess it helps to mention that I'm using the development web server with manage.py runserver.


EDIT:
Turns out runserver can't serve static files, unfortunately I didn't know this was what the problem was. God drat it, I wasted like 2 hours trying to figure this out. I was able to get it running in our test environment by adding this to our urls.py. I'll be removing it once we deploy it, but I just wish this had been better documented.
code:
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/media'}),

Janitor Prime fucked around with this message at 20:50 on Nov 17, 2008

tankadillo
Aug 15, 2006

I'm having a nightmare trying to get Django to handle comments the way I want. Setting up the default system was fairly easy, but customizing it seems impossible. Basically all I want to do is make the name and email field optional, but it doesn't seem like that's doable. Whenever I try to render a custom comment form it completely ignores the changes I make. Is there something I'm doing wrong or does Django just suck?

form:
code:
class CommentForm(forms.Form):
  name = forms.CharField(label='Your name',initial='Anonymous', required=False)
  email = forms.EmailField(label='Your email address',initial='name@example.com', required=False)
view:
code:
...
return render_to_response('entry.html',{'entry': entry,'CommentForm' : CommentForm(),})
...
template:
code:
{% get_comment_form for entry as CommentForm %}
<form action="{% comment_form_target %}" method="POST">
  <table>
  {{ CommentForm.as_table }}
  </table>
  <p class="submit">
    <input type="submit" name="submit" class="submit-post" value="Preview">
  </p>
</form>
I expect it to recognize my custom values for label, initial, and required, but it just replaces those with the defaults. What's even the point to making a custom form object if it disregards all your changes?

tankadillo fucked around with this message at 00:12 on Nov 19, 2008

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
What are you doing with the form after it's submitted? If you're trying to populate an instance of a comment model you've made, you should use a model-based form and make sure the optional fields are set as such in the model. If you're not using models... you need to post more code to explain what you're doing.

tankadillo
Aug 15, 2006

After studying the documentation some more and messing around it looks like I had misunderstood how it was supposed to work, I've got it mostly figured out now. Their documentation was really unhelpful for me, I had to use google to find some random blog posts to help me out :\ But oh well I got it now.

WickedMetalHead
Mar 9, 2007
/dev/null
Does unique_for_month still work?

I tried having a BooleanField set with unique_for_month="date" and also a CharField with choices and null/blank = True set to unique_for_month="date" and in both cases it allowed me to check the field twice or pick a choice twice.

king_kilr
May 25, 2007

WickedMetalHead posted:

Does unique_for_month still work?

I tried having a BooleanField set with unique_for_month="date" and also a CharField with choices and null/blank = True set to unique_for_month="date" and in both cases it allowed me to check the field twice or pick a choice twice.

Right now, in model forms, the only thing that's validated is unique, and unique together(I'm the guy who wrote that). Properly validating for everything isn't going to happen until 1.1, when ticket #6845 get's fixed, that ticket is model validation, and amongst other things it will handle propogating all validation on the model to the form level.

MrMoo
Sep 14, 2000

Are there any django basic image hosting examples?

:effort:

Basically looking at basic authentication to upload images via HTTP upload or site transload, create thumbnails if larger than 800x600, and show BB code links. Must handle duplicate file names, and check for invalid data when transloading due to referrer checking, etc.

There are a tonne of PHP scripts but most appear to add extra fluff not required for individual hosting. Unless I'm missing something a DB should not be necessary.

nbv4
Aug 21, 2002

by Duchess Gummybuns
Does anyone have any experience using django-tagging with django 1.0? Is it stable? or alternatively a tagging system that works well with 1.0?

king_kilr
May 25, 2007

nbv4 posted:

Does anyone have any experience using django-tagging with django 1.0? Is it stable? or alternatively a tagging system that works well with 1.0?

yeah it should work fine, you need to use the newforms-admin branch though.

bitprophet
Jul 22, 2004
Taco Defender

nbv4 posted:

django 1.0

king_kilr posted:

newforms-admin branch

:confused: Is there some sort of neo-newforms-admin that continues to exist/be relevant post-1.0?

king_kilr
May 25, 2007

bitprophet posted:

:confused: Is there some sort of neo-newforms-admin that continues to exist/be relevant post-1.0?

Not nfa within django itself, but the nfa branch on django-tagging, it just hasn't been updated yet I guess.

nbv4
Aug 21, 2002

by Duchess Gummybuns

king_kilr posted:

yeah it should work fine, you need to use the newforms-admin branch though.

yeah I installed it from svn, and it seem to be working all right so far.

Now I have another problem. I decided to split up one model into two models. Originally I had a model called "Music" which contained both CD's and records. Now I have one model for CD's, and another one for records.

I want to create a paginator that displays both CD's and records in order of date of release. Whats the best way to do this? Shpuld I make another model that somehow contains both all of the user's CD's and all of the user's records?

this is a stripped down snipplet of my code so far:

code:
########### in models.py ############

class CD(models.Model)
    release_date = models.DateField()
    name = models.CharField()

class Record(models.Model)
    release_date = models.DateField()
    name = models.CharField()

########### in views.py ############

from django.core.paginator import Paginator, InvalidPage, EmptyPage
	
cds = CD.objects.all()
records = Record.objects.all()

music = #??????

paginator = Paginator(music, per_page=profile.per_page, orphans=5)		

Murodese
Mar 6, 2007

Think you've got what it takes?
We're looking for fine Men & Women to help Protect the Australian Way of Life.

Become part of the Legend. Defence Jobs.
How do I stop recursive foreign keys from being able to choose themselves? I don't want a category to be able to pick itself as its parent :V

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
:argh: THEY CHANGED THE DOCS INDEX PAGE AGAIN

You're gonna have to create a custom field (inherit from forms.ModelChoiceField) or use a form validator on whichever form you use to create the categories. All you have to do is check that the id field of the object doesn't match the foreign key id.

king_kilr
May 25, 2007

Murodese posted:

How do I stop recursive foreign keys from being able to choose themselves? I don't want a category to be able to pick itself as its parent :V

I'd just create a custom model form for use in the admin and elsewhere that has a clean_<my_fkey> method which throws a validation error if cleaned_data['my_fkey'] == self.model.id

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

nbv4 posted:

Now I have another problem. I decided to split up one model into two models. Originally I had a model called "Music" which contained both CD's and records. Now I have one model for CD's, and another one for records.

I want to create a paginator that displays both CD's and records in order of date of release. Whats the best way to do this? Shpuld I make another model that somehow contains both all of the user's CD's and all of the user's records?

this is a stripped down snipplet of my code so far:

(snip)

Check out model inheritance in the Django docs. I'd suggest making an abstract model called Music, then have CD and Record inherit from Music. Put your release_date and name fields in the Music model, then take them out of both CD and Record. Then, in your view, you just go Music.objects.all().order_by('release_date') and you're set.

What's going on here? An abstract model defines certain fields and lets you use the model as normal in Django, but in the database there's no mention of the abstract model. Instead, any submodels of the abstract model get (inherit) the abstract model's fields automatically. So in my outline above, both CD and Record get the release_date and name fields (which end up as columns in their respective database tables); Django will then interpret Music.objects.all() as you wanting all objects of models descending from Music, even though "Music" doesn't exist outside of Django; all of the tables that make up Music-derived models get joined together. Thus, any fields common to all Music should go in the Music model. You can, of course, specify more fields on a submodel (e.g. give Records a rotation speed), but you wouldn't be able to refer to it from the Music model (e.g. Music.objects.all().order_by('rotation_speed') won't do you much good).

Wedge of Lime
Sep 4, 2003

I lack indie hair superpowers.

nbv4 posted:

Does anyone have any experience using django-tagging with django 1.0? Is it stable? or alternatively a tagging system that works well with 1.0?

The following bug caused me some pain:

http://code.google.com/p/django-tagging/issues/detail?id=160

Also, there are a couple of issues with the parsing of tags if you aren't forcing lowercase tags.

All in all its a great library and I'm happily using it with Django 1.0.

bitprophet
Jul 22, 2004
Taco Defender

deimos posted:

:argh: THEY CHANGED THE DOCS INDEX PAGE AGAIN

Right, but it's a lot better now than the first version post-Sphinxification -- I can actually find poo poo with browser find on the index page now. There was no excuse for a Web framework's doc landing page to not mention the word "URL" anywhere :v:

Adbot
ADBOT LOVES YOU

nbv4
Aug 21, 2002

by Duchess Gummybuns

pokeyman posted:

Check out model inheritance in the Django docs. I'd suggest making an abstract model called Music, then have CD and Record inherit from Music. Put your release_date and name fields in the Music model, then take them out of both CD and Record. Then, in your view, you just go Music.objects.all().order_by('release_date') and you're set.

What's going on here? An abstract model defines certain fields and lets you use the model as normal in Django, but in the database there's no mention of the abstract model. Instead, any submodels of the abstract model get (inherit) the abstract model's fields automatically. So in my outline above, both CD and Record get the release_date and name fields (which end up as columns in their respective database tables); Django will then interpret Music.objects.all() as you wanting all objects of models descending from Music, even though "Music" doesn't exist outside of Django; all of the tables that make up Music-derived models get joined together. Thus, any fields common to all Music should go in the Music model. You can, of course, specify more fields on a submodel (e.g. give Records a rotation speed), but you wouldn't be able to refer to it from the Music model (e.g. Music.objects.all().order_by('rotation_speed') won't do you much good).

Actually an abstract model can't be used here because the only use they have is prototyping other models. You can't call managers or anything else on abstract models. But a "multi-table" inheritance seem to work OK so far...

edit: If I run "music = Music.objects.all()", it returns a list of Music objects. How can I tell if a Music object is representing a CD or a record? I realize you can do "music.record.rotation_speed", but how can I tell which one it is?

nbv4 fucked around with this message at 21:38 on Nov 23, 2008

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply