I'm in new territory with Django/Python. I'm building a site where the user selects from a list of available services, and then enters info about the services.
I didn't want to keep the service list in the database, becasue that's really more site configuration info rather than user info. So I'm setting them as an Object Class (recommended by a friend)
class Service(object):
def __init__(self, name, sections, link, enabled=True):
self.name = name
self.link = link
self.sections = sections
开发者_运维百科 self.enabled = enabled
SERVICES = {
'SERVICE1': ArtistService(
'Service Name',
['Section Name 1','Section Name 2',],
'http://www.service.com',
),
Is it possible to use this class as a foreign key in the database? I'd like to retreive some information about the service from the class though a template join. Example:
{% for s in user_activated_services %}
{{ s.service.name }}
{% endfor %}
But it's not working because I'm just saving the key in a CharField in the user_activated_services model:
class ActivatedServices(models.Model):
user_page = models.ForeignKey(Page)
service = models.CharField(max_length=20, choices=[(k, s.name) for k, s in userservices.services.SERVICES.iteritems()])
When I try to replace with a foreign key, I get an error of "First parameter to ForeignKey must be either a model, a model name, or the string 'self'"
Anyway, I think I know the problem, I just can't fix it. Hope this is enough info. I'm sure I'm missing something stupid.
Thanks in advance.
Is it possible to use this class as a foreign key in the database?
No.
Only models.Model
classes can be used as foreign keys.
"Foreign Key" is a database concept.
If you want to have non-database things as foreign keys, they're just strings or numbers and the "reference" is a simple mapping that you manage in your code.
精彩评论