Django admin many to many table name - django

Can I specify the name I want for the many to many table?

Yes. See Table Names for all of the exciting details.
Update: OK, then perhaps the related_name option is what you are looking for. There are some caveats covered here.
Updatex2: OK, Kelvin gets a star for answering his own question! It's been an age since I perused the Django Meta Model Options, but, in retrospect, that's where we should have started.
BTW, wandering through the django/db/ code on only half a cup of coffee is definitely a challenge.

You define the table name using the db_table option when declaring the ManyToManyField attribute. See example below:
class revision(models.Model):
revision_id = models.AutoField(primary_key=True)
issue_list = models.ManyToManyField(issue, related_name='revisions', db_table='issue_revision')
related_name is the field by which this class will be seen by issue, meaning, you will access it as my_issue.revisions(). And the table being used in the DB is named issue_revision.

Related

Creating a nested form field or something like that

I'm not entirely sure about the correctness of the question. In fact, I doubt whether I can express exactly what I am looking for.
Question: How can I create additional fields based on the previous selection before submitting the form?
Let's take the number of pets and the name of the pet in our example. I want how many pet names to be entered first
class UrlForm(forms.Form):
INT_CHOICES = [(x, x) for x in range(11)]
number_of_pets = forms.ChoiceField(choices=INT_CHOICES)
and then create as many Charfield fields as the selected value based on the previous selection:
#new fields as many as the number of pets
pet1 = forms.CharField()
pet2 = forms.CharField()
Of course, the variable name issue is a separate issue.
Question 2: As an alternative approach, can I create a pet name field like a tag field? As in the image:
Image taken from here. The question is appropriate but a ReactJs topic.
You can share the topic, title, term, article, anything that I need to look at. Thanks in advance.
Edit:
The pet example is purely fictional. Influenced by the image, I used this topic.

How do I create multiple One-to-Many relationships to the same table in Django?

So first off, I want to clarify that I am trying to make One-To-Many relationships, not Many-to-One. I already understand how ForeignKeys work.
For the sake of the discussion, I've simplified my models; they're much more field-rich than this in the real implementation.
I have a model, called a ColumnDefinition:
class ColumnDefinition(Model):
column_name = CharField(max_length=32)
column_type = PositiveSmallIntegerField()
column_size = PositiveSmallIntegerField(null=True, blank=True)
I think have a registry. Each registry has a separate set of columns for it's input and output definition. I've put the theoretical "OneToManyField" in there to demonstrate what I'm trying to do.
class Registry(Model):
input_dictionary = OneToManyField(ColumnDefinition)
output_dictionary = OneToManyField(ColumnDefinition)
created_date = DateTimeField(auto_now_add=True, editable=False)
A ColumnDefinition is only ever related to one Registry ever. So it's not a Many to Many relationship. If I put a ForeignKey on the ColumnDefinition instead to create a reverse relationship, it can only create a single reverse, whereas I need both an input and output reverse.
I don't want to have to do anything kludgey like adding a "column_registry_type" field onto ColumnDefinition if I can get around it.
Does anyone have any good ideas on how to solve this problem?
Thanks!
You can add two ForeignKeys on ColumnDefinition, one for input and one for output, and give them separate related_names:
class ColumnDefinition(Model):
...
input_registry = models.ForeignKey(Registry, related_name='input_columns')
output_registry = models.ForeignKey(Registry, related_name='output_columns')
You can then access the set of columns like registry.input_columns.
You can and should define two different ForeignKey fields on ColumnDefinition. Just make sure to specify a related_name value for at least one of them.
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name

Let user create variables (and their data-type) - Django

I am trying to write a Django app that does the following:
A user sees various articles and then codes variables against these articles.
i.e.:
Article is about Egypt.
User assigns: country = Egypt
This, so far, is easy.
What I would love to have, though, is that the user can create the variables himself, without me having to hard-code them into models.
How do I best do this?
Should I use the through-relationship on a manytomany-field or are there other, better, ways to do this?
If I use the through-relationship, how can I let the user choose what data-type the variable should be?
Should I put a field for every fieldtype into the through-model and then have the user choose it somehow?
I know, this is more than one question, but if you answer my first question I would be very happy!
I am assuming that by "user" you mean other apps that are based on the app that contains Article.
Use model inheritance:
https://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance
class Article(models.Model):
pub_date = models.DateTimeField(...)
class CountryArticle(Article):
country = SomeSuitableModel()

Foreign Key Relationships

I have two models
class Subject(models.Model):
name = models.CharField(max_length=100,choices=COURSE_CHOICES)
created = models.DateTimeField('created', auto_now_add=True)
modified = models.DateTimeField('modified', auto_now=True)
syllabus = models.FileField(upload_to='syllabus')
def __unicode__(self):
return self.name
and
class Pastquestion(models.Model):
subject=models.ForeignKey(Subject)
year =models.PositiveIntegerField()
questions = models.FileField(upload_to='pastquestions')
def __unicode__(self):
return str(self.year)
Each Subject can have one or more past questions but a past question can have only one subject. I want to get a subject, and get its related past questions of a particular year. I was thinking of fetching a subject and getting its related past question.
Currently am implementing my code such that I rather get the past question whose subject and year correspond to any specified subject like
this_subject=Subject.objects.get(name=the_subject)
thepastQ=Pastquestion.objects.get(year=2000,subject=this_subject)
I was thinking there is a better way to do this. Or is this already a better way? Please Do tell ?
I think what you want is the related_name property of the ForeignKey field. This creates a link back to the Subject object and provides a manager you can use to query the set.
So to use this functionality, change the foreignkey line to:
subject=models.ForeignKey(Subject, related_name='questions')
Then with an instance of Subject we'll call subj, you can:
subj.questions.filter(year=2000)
I don't think this performs much differently to the technique you have used. Roughly speaking, SQL performance boils down a) whether there's an index and b) how many queries you're issuing. So you need to think about both. One way to find out what SQL your model usage is generating is to use SqlLogMiddleware - and alternatively play with the options in How to show the SQL Django is running It can be tempting when you get going to start issuing queries across relationships - e.g. q = Question.objects.get(year=2000, subject__name=SUBJ_MATHS) but unless you keep a close eye on these types of queries, you can and will kill your app's performance, badly.
Django's query syntax allows you to 'reach into' related objects.
past_questions = Pastquestion.objects.filter(year=2000, subject__name=subject_name)

Does order of declaration matter in models.py (Django / Python)?

I have something like this in models.py
class ZipCode(models.Model):
zip = models.CharField(max_length=20)
cities = City.objects.filter(zip=self).distinct()
class City(models.Model):
name = models.CharField(max_length=50)
slug = models.CharField(max_length=50)
state = models.ForeignKey(State)
zip = models.ManyToManyField(ZipCode)
When I do this I get:
NameError: name 'City' is not defined
Is this because the order of declaration matters? And if so, how can I do this, because either way I arrange this, it looks like I'm going to get a NameError.
Thanks.
Apart from order issues, this is wrong:
cities = City.objects.filter(zip=self).distinct()
It is not inside a method, so "self" will also be undefined. It is executed only once, at class-creation time (i.e. when the module is first imported), so the attribute created would be a class attribute and have the same value for all instances. What you might be looking for is this:
#property
def cities(self):
return City.objects.filter(zip=self).distinct()
Because this is inside a method, which is not executed until it's accessed, ordering issues will no longer be a problem. As ozan points out, this is a duplication of what Django reverse relations already give you for free:
a_zip_code.city_set.all()
And you can use related_name to call it what you like:
zip = models.ManyToManyField(ZipCode, related_name='cities')
...
a_zip_code.cities.all()
So I don't think the ordering issue you originally asked about is even relevant to your situation. When it is, others have already pointed out using quoted strings in ForeignKey and ManyToManyField declarations to get around it.
When you have references to classes defined after, you can use this trick:
attribute = models.ForeignKey('ClassDefinedAfterThis')
Yes order does matter as others have noted.
Though, encountering this issue is almost always going to be an indication that you're doing something wrong.
In this case your declaration:
cities = City.objects.filter(zip=self).distinct()
... is both redundant and bad practice. You can find the cities related to a zip code by referring to that zip code's city_set in your views (ie not in your model!). So if zip is an instance of ZipCode, you would do:
cities = zip.city_set.all()
If you really want to call it 'cities' rather than 'city_set' you can use the related_name parameter in your m2m declaration.
I was once worried about order... because I thought my models below could only reference models above. But then realized that you can just do a
models.ForeignKey('appName.modelName')
and all was fine.
Yes, order does matter, but your example does not look right to me. I think you should just be using a foreign key for your many-to-one relationship:
cities = models.ForeignKey(City)
This has the details on many-to-one relationships with django models.
Edit:
It was pointed out to me in the comments that cities in Europe might have several cities in the same zip code. If you are looking for a many-to-many relationship here, you should use:
cities = models.ManyToManyField(City)
This is described in Django's documentation. The point is, this is either of these examples are much more clear than what is used in the example.
Order matters in Python. This thread may be relevant to your question. Also for your uses, you may want to use a unique foreign key in the ZIP code class.