Find table by name - Django - python

How I can find table by name in code python?
Example:
class AlexAlex(models.Model):
title = models.CharField(max_length=255)
message = models.TextField()
dataMsg = models.DateField()
fromMsg = models.CharField(max_length=255)
readMsg = models.BooleanField(default=False)
def __str__(self):
return self.title
and now I want to find the class name as it has some username.
Example in code:
UserLogged = "AlexAlex" or UserLogged = "Alex alex" + "s" // Example name user logged
Table = functionWhichFindTablebyName(UserLogged) // Find table by name
Table.objects.get.all()
Can I do like this?I want that use for 'box mail users'.I have a lot of table and I don't wanna write manual in import/from.

I feel that this reflects a poorly implemented thing that needs a second though. It sounds like you are creating a table for each user, and storing there the messages for that user, when you should create a table Message related to User. That being said, if you want to retrieve an object (a table) from a module:
from any_app import models
getattr(models, "AlexAlex").objects.all()
Django also offers ContentTypes, which allows you to do the things you ask for without having to import the models. E.g.
from django.contrib.contenttypes.models import ContentType
obj = ContentType.objects.get(app_label="any_app", model="alexalex")
obj.model_class().objects.all()
# Or p.get_all_objects_for_this_type(kwargs)

Related

How to connect models from different apps in Django?

I have a few apps within my Django project. There are two apps that I am currently working with "Application" and "User" and I have two questions related to models:
Question 1:
I want to design it in such a way so that external users submit their contact form on Application/templates/Application/Apply.html and the info would get added to the database. Internal users would be able to add external users as well but from a different template: User/templates/User/AddNewContact.html
I am able to add a new contact from an internal user's perspective:
User/models.py
class Contact(models.Model):
ContactName = models.CharField(max_length = 250, default='')
ContactResidence = models.CharField(max_length = 250, default='')
Tel = models.CharField(max_length = 250, default='')
def get_absolute_url(self):
return reverse('User:ContactDetails', kwargs={'pk': self.pk}
)
def __str__(self):
return self.ContactName
class Locations(models.Model):
contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
Country = models.CharField(max_length=250, default='')
def __str__(self):
return self.Country
I was going to just copy this model and paste it into Application/models.py but there are two problems:
1) I don't want external users to be directed to URL: User:ContactDetails and technically, it is not going to work out because I will build the authentication later on.
2) I feel that by copying and pasting I am breaking the 'don't repeat yourself" rule.
Should I connect two models using the foreign keys? What are the best practices in this case?
Question 2
Am I working with one-to-many relationship according to the model provided? I want to have one contact with his personal info (tel/email/address) and a number of branch locations across the world associated with that contact.
To be used a relationship one to many, you can be doing as after:
On models of father app (father table):
class Department(models.Model):
dept_id = models.AutoField(primary_key=True)
On models of child app (child table):
from appname.models import Department
class Office(models.Model):
office_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
dept = models.ForeignKey(Department, on_delete=models.CASCADE)
It helped me.
Question 1: Well, you don't need to copy paste the model. You can use models from other django apps anytime, just need to import it. Basically what you should do is, instead of linking the url directly to the template in the Applications app, you should connect it to a view. In the view file you can import the models from User.models import *, and use them normally.
Question 2: As far as I understand the question your structure provides what you want: one contact (with personal info) associated with several countries. Except that you should replace Agent by Contact in contact = models.ForeignKey(Agent, on_delete=models.CASCADE)
Question 1: Note that the 'get_absolute_url' method is only called if you don't provide a success url in your view. If you are using a CreateView or FormView you can specify the success url by overriding the get_success_url method, for example:
class ContactCreateView(CreateView):
model = Contact
fields = ['ContactName', 'ContactResidence', 'Tel']
def get_success_url(self):
if not self.request.user.internal: # e.g. internal is a User bool field
return HttpResponseRedirect('some/external/url/')
return super().get_success_url() # call get_absolute_url model method.
The DRY principle is respected.
Question 2: Yes, the question you need to ask yourself is 'does a model instance (In this case Contact) have many instances of another model (Location)?' If the answer is yes, then the M2M field should go into your Contact model. See the django docs explaining the pizza/toppings example.
The apps should be in the same project and you can import one model as:
import appName.models or
from appName.models import ClassName
In app2 models you can use foreignKey or manyTomany after importing the class:
from appsName.models import ClassName
class Person(models.Model):
con = ForeignKey(ClassName)

Models referring to each other - how can I most efficiently fix this issue?

I have a Django application that contains two models - Company and User. These are each in separate files. Each User has a Company by a model.ForeignKey field:
company.py:
class Company(models.Model):
name = models.CharField(max_length=32)
is_admin = models.BooleanField(default=False)
user.py:
# Ignore the clumsy in this import for a moment
from package.models.company import Company
class User(models.Model):
name = models.CharField(max_length=32)
company = models.ForeignKey(Company)
Now, one thing I want to do is to add a method list_admins to Company (not User), whereby it would give me a list of all users who happen to have is_admin set to True:
def list_admins(self):
return User.object.filter(is_admin=True);
But of course that would require me to import User in Company, which I can't, as I can't import User in Company and Company in User at the same time owing to its circularity.
So how does one resolve this in a Pythonic/Djangoic way?
You can use the reverse ForeignKey relation on each Company to access their respective Users:
def list_admins(self):
return self.user_set.filter(is_admin=True)
Doc. reference: Following relationships “backward”
def list_admins(self):
return User.object.filter(company__is_admin=True);

how to display many error django

i have following models
class tags(models.Model):
tag = models.CharField(max_length=15) # Tag name
tagDescription = models.TextField() # Tag Description
tagSlug = models.TextField() # Extra info can be added to the existing tag using this field
class stores(models.Model):
storeName = models.CharField(max_length=15) # Store Name
storeDescription = models.TextField() # Store Description
storeURL = models.URLField() # Store URL
storePopularityNumber = models.IntegerField(max_length=1) # Store Popularity Number
storeImage = models.ImageField(upload_to=storeImageDir) # Store Image
storeSlug = models.TextField() # This is the text you see in the URL
createdAt = models.DateTimeField() # Time at which store is created
updatedAt = models.DateTimeField() # Time at which store is updated
storeTags = models.ManyToManyField(tags)
class tagsAdmin(admin.ModelAdmin):
list_display = ('tag', 'tagDescription', 'tagSlug')
class storesAdmin(admin.ModelAdmin):
list_display = ('storeName','storeDescription','storeURL',
'storePopularityNumber','storeImage',
'storeSlug','createdAt','createdAt','storeTags'
)
admin.site.register(tags,tagsAdmin)
admin.site.register(stores,storesAdmin)
Whenever I am trying to run command : python manage.py syncdb
I got the error: django.core.exceptions.ImproperlyConfigured: 'storesAdmin.list_display[8]', 'storeTags' is a ManyToManyField which is not supported.
I don't understand what I am doing wrong here. I want to simply display all the models in the django admin site.
You can't reference a Many2ManyField like that, you have to use a method instead in the stores class that looks like this
def get_tags():
return self.storeTags.all()
and reference that in your list_display(...'get_tags')
This is done because the M2M field would result in lots of SQL queries that would slow the entire thing down so therefore the choice would have to come from the developer and not from the framework.
Please check:
ModelAdmin.list_display
"ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.)"
You can use a custom method to show values of ManyToManyField or simply remove storeTags from list_display

Django import problem with models.py and multiple ManyToManyFields()

I am working on creating a simple contest submission system using django. This is my first real django project. Basically each user can view a list of problems, submit a file, and view a results page.
Each problem can be associated with multiple contests, and different contests can use the same problem. Because of this, both problem and contest have a manyToManyField with each other. This is what is causing my problem.
Here is the initial models.py implementation I am going with:
startfile
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
class Problem(models.Model):
name = models.CharField(max_length=50)
filename = models.CharField(max_length=300)
contests = models.ManyToManyField(Contest)
class Contest(models.Model):
name = models.CharField(max_length=50)
problems = models.ManyToManyField(Problem)
date = models.DateField()
class Submission(models.Model):
user = models.ForeignKey(User)
problem = models.ForeignKey(Problem)
filename = models.CharField(max_length=300)
endfile
Is there a simple way to fix this? Or should I rethink my entire layout? I tried breaking each class into its own django app but I don't think thats how I should do it. The error I get is that Contest can not be found (because it exists lower in the file).
All advice is appreciated!
You don't need a ManyToManyField in both Contest and Problem. Many-to-many fields are already bidirectional. Just put it on one - doesn't matter which.
Djano will automatically create the reverse relation for you, so you only need to create it one end, eg.
class Problem(models.Model):
name = models.CharField(max_length=50)
filename = models.CharField(max_length=300)
contests = models.ManyToManyField(Contest, related_name='problems')
related_name gives you the possibility to assign a name to the reverse relation. Without defining the relation on the Contest model, you can then access eg. a_contest.problems.all()!

python code for django view

MODEL:
class Pathology(models.Model):
pathology = models.CharField(max_length=100)
class Publication(models.Model):
pubtitle = models.TextField()
class Pathpubcombo(models.Model):
pathology = models.ForeignKey(Pathology)
publication = models.ForeignKey(Publication)
List of pathology sent to HTML template as drop down menu
VIEW:
def search(request):
pathology_list = Pathology.objects.select_related().order_by('pathology')
User selects one pathology name from drop down menu and id retrieved by
VIEW:
def pathology(request):
pathology_id = request.POST['pathology_id']
p = get_object_or_404(Pathology, pk=pathology_id)
Where I'm stuck. I need the python/django syntax to write the following:
The pathology_id must now retrieve the publication_id from the table Pathpubcombo (the intermediary manytomany table). Once the publication_id is retrieved then it must be used to retrieve all the attributes from the publication table and those attributes are sent to another html template for display to the user.
you should be using many-to-many relations as described here:
http://www.djangoproject.com/documentation/models/many_to_many/
Like:
class Pathology(models.Model):
pathology = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
class Publication(models.Model):
pubtitle = models.TextField()
Then
def pathology(request):
pathology_id = request.POST['pathology_id']
p = get_object_or_404(Pathology, pk=pathology_id)
publications = p.publications.all()
return render_to_response('my_template.html',
{'publications':publications},
context_instance=RequestContext(request))
Hope this works, haven't tested it, but you get the idea.
edit:
You can also use select_related() if there is no possibility to rename tables and use django's buildin support.
http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4

Categories

Resources