I am creating an app in which I want to query all the members and their status. but I am getting above error.
these are my both models.
class Member(models.Model ):
user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE)
com = models.ForeignKey(Committee, on_delete=models.CASCADE,verbose_name='Committee Name')
class PaymentDetail(models.Model):
mem = models.ForeignKey(Member,on_delete=models.CASCADE, related_name='payment_details', verbose_name='Memeber Phone no')
com = models.ForeignKey(Committee, on_delete=models.CASCADE,related_name='committee_details',verbose_name='Committee Name')
payment_month = models.DateField(default=datetime.now())
payment_status = models.CharField(max_length=16, choices=PAYMENT_DETAILS_CHOICES, default="1")
First I am getting all the members by (members.objects.all() then looping over like this
for member in members:
member.payment_details.payment_status
but I am getting this error related manager has no attribute.
actually I can get data from PaymentDetail.objects.all() but it will only show data from PaymentDetail table. I want all the members and next to them their status from PaymentDetail table
You have ForeingKey relation, this is relation one to many, if you wanna access to payment_details you have to ask for all related objects by payment_details.all().
Consider using one to one relation (https://docs.djangoproject.com/en/4.0/topics/db/examples/one_to_one/)
, after change to one to one relation this member.payment_details.payment_status will be work.
Related
I want to do a lookup that spans three model classes. I want to find all the PartListings that match the Specific_part in the ListItem. Say Specific part = Radio, there could be several Radios in the PartListings and I want to return the PartListing id of all of them so that I can get other attributes like quantity.
I have these models:
class SpecificPart(BaseModel):
class PartListing(BaseModel):
specific_part = models.ForeignKey(
SpecificPart, on_delete=models.CASCADE, blank=True, null=True,
related_name="part_listing")
class ListItem(BaseModel):
specific_part = models.ForeignKey(SpecificPart, on_delete=models.CASCADE,
related_name="listitem")
I'm trying to put the lookup under the ListItem class like this:
def item_match(self):
part = self.specific_part
return PartListings.filter(specific_part__specific_part=part)
I tried to set it up as a Lookup that spans relationshipsbut am getting an error that PartListing is not defined. I also suspect that I'm referencing the foreign keys incorrectly. I'm also ok with redefining the models if a One to One would be better.
I am a Django newbie so thanks so much for your help!
You can try like this using reverse relation between SpecificPart and PartListing models:
class ListItem(BaseModel):
...
def item_match(self):
return self.specific_part.part_listing.all()
I am implementing a web interface for email lists. When a list administrator logs in, the site will visually display which lists they are an owner of and corresponding information about the lists. For this I have decided to have two tables:
1) An owner table which contains entries for information about list administrators. Each of these entries contains a 'ManyToManyField' which holds the information about which lists the owner in any given entry is an administrator for.
2) A list table which contains entries with information about each email list. Each entry contains the name of the list a 'ManyToManyField' holding information about which owners are administrators the list.
Here is the code in models.py:
from django.db import models
class ListEntry(models.Model):
name = models.CharField(max_length=64)
owners = models.ManyToManyField('OwnerEntry')
date = models.DateTimeField('date created')
class Meta:
ordering = ('name',)
class OwnerEntry(models.Model):
name = models.CharField(max_length=32)
lists = models.ManyToManyField('ListEntry')
class Meta:
ordering = ('name',)
I have already set up a simple local database to create a basic working website with. I have populated it with test entries using this code:
from list_app.models import *
from datetime import *
le1 = ListEntry(
name = "Physics 211 email list",
date = datetime.now(),
)
le1.save()
le2 = ListEntry(
name = "Physics 265 email list",
date = datetime(2014,1,1),
)
le2.save()
oe1 = OwnerEntry(
name = 'wasingej',
)
oe1.save()
oe1.lists.add(le1,le2)
le1.owners.add(oe1)
le2.owners.add(oe1)
oe2 = OwnerEntry(
name = 'doej',
)
oe2.save()
oe2.lists.add(le1)
le1.owners.add(oe2)
Here is where my error occurs: When the user has logged in via CAS, I have them redirected to this page in views.py:
def login_success(request):
u = OwnerEntry(name=request.user)
print(u.name)
print(u.lists)
return HttpResponse("login success!")
At the line 'print(u.lists)', I get the error "" needs to have a value for field "ownerentry" before this many-to-many relationship can be used.
What am I doing wrong here?
Your model structure is broken, for a start. You don't need ManyToManyFields on both sides of the relationship, only one - Django will provide the accessor for the reverse relationship.
Your issue is happening because you are not querying an existing instance from the database, you are instantiating an unsaved one. To query, you use model.objects.get():
u = OwnerEntry.objects.get(name=request.user.username)
You need to provide the actual class to the ManyToManyField constructor, not a string.
https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/
I am reading Excel using xlrd. One of the columns has the Bank name, which is linked to vehicle model via Foreign Key. When xlrd finishes reading a row, it should save that record to vehicle table. However getting the actual pk value and error that Vehicles.bank must a Banks instance.
After checking dozens of questions related to this issue, I found this one the most similar one, but still I am not getting the expected result.
The relevant Vehicle model section is as follows:
class Vehicles(models.Model):
stock = models.CharField(max_length=10, blank=False, db_index=True)
vin = models.CharField(max_length=17, blank=False, db_index=True)
sold = models.DateField(blank=True, null=True, db_index=True)
origin = models.CharField(max_length=10, blank=False, db_index=True)
bank = models.ForeignKey('banks.Banks', db_column='bank', null=True)
I am using python 2.7, django 1.5.4 and Postgresql 9.2.5. Dbshell utility does show that banks table has a Foreign contraint referring to vehicles table, via banks(id).
Since I am not using a form for this particular part, I think it does not matter whether I use a ModelForm or not.
Current scenario: Excel file has FBANK as the cell value. There is an existing record in banks table that contains FBANK in its name column, id=2. The python line is:
def bank(value):
return Banks.objects.get(name=value).id
With the above line, error is:
Cannot assign "2": "Vehicles.bank" must be a "Banks" instance.
If I remove the ".id" at the end, error is then:
Banks matching query does not exist.
Appreciate your help.
Ricardo
When saving Vehicle you need to pass Banks instance with corresponding bank name. See example, I suppose that you have all data in corresponding cells from 0 to 4, replace with your own cells numbers:
def get_bank_instance(bank_name):
try:
bank = Banks.objects.get(name=bank_name)
except Banks.DoesNotExist:
return None
return bank
# reading excel file here, we have list of cells in a row
for cell in cells:
bank = get_bank_instance(cell[4])
if bank:
# get other cells values to be saved in Vehicles
stock, vin, sold, origin = cell[0], cell[1], cell[2], cell[3]
Vehicles.create(bank=bank, stock=stock, vin=vin, sold=sold, origin=origin)
You also can create save instance of Vehicles passing bank id directly:
b_id = Banks.objects.get(name=bank_name).id
Vehicles.create(bank_id=b_id, stock=stock, vin=vin, sold=sold, origin=origin)
Update:
create() is a built-in model method to create and save into database model instance. If you are asking about "Add a classmethod on the model class" in Django docs, this is not the case, because you are just using built-in method for the model. For some cases you can use custom method for creating new models, but I would do so if I had to pass a lot of default attributes for the new instance.
Also, it's possible to create and save new model instance by using save():
bank_instance = Banks.objects.get(name=bank_name)
vehicle = Vehicles()
vehicle.bank = bank_instance
vehicle.stock = stock
vehicle.vin = vin
vehicle.sold = sold
vehicle.origin = origin
# without save() data will not be saved to db!
vehicle.save()
It's quite long and you always need to remember to call .save(), so it's a good idea to use .create()
You should be returning a Banks instance when you want to assign it to a Vehicle model instance; so you should not have the .id part at the end of the return value for your bank() method.
Secondly, if it says that it isn't finding the Banks instance, then you should check the value of your value parameter to see what it is and try to manually do a Banks.objects.get from your database. If it can't be found then there is probably another reason for this other than using the Django ORM incorrectly.
When you are assigning instances to other instances in Django, for example setting the Bank for a Vehicle it must be an instance of the model and not the id or pk value of model; this is stated in the other StackOverflow question that you reference in your question.
So I'm using inheritance in django with the following classes:
class main_menu(node):
"""
main_menu(node)
Has no extra fields. All children of the root node must
be main_menu nodes
"""
# Required for tree hierarchy to work (db_column='path' for raw queries)
_path1 = models.CharField(db_column='path', max_length=Global.MAX_FILE_PATH_LENGTH, unique=True);
main_menu_blah = models.CharField(max_length=30, default='');
def __unicode__(self):
return self.main_menu_blah;
main_menu
class language(main_menu):
"""
language(main_menu)
Main menu used specifically for a main menu targetted
at a speaker of some language.
"""
# Required for tree hierarchy to work
_path2 = models.CharField(db_column='path', max_length=Global.MAX_FILE_PATH_LENGTH, unique=True);
language_blah = models.CharField(max_length=30, default='');
def __unicode__(self):
return self.language_blah;
language
class language2(language):
_path3 = models.CharField(db_column='path', max_length=Global.MAX_FILE_PATH_LENGTH, unique=True);
language_blah2 = models.CharField(max_length=30, default='');
Now, I can insert access all of these models just fine as long. I can also get them using .objects.get(...).
But if I delete a row from a parent class table (such as language which is a parent to language2), then I cannot get() the last row from the language2 table.
I execute:
subNode = language2.objects.get(_path3=);
I always get the following error:
DoesNotExist
language2 matching query does not exist.
And I've looked in the database (sqlite) and I can see that the last entry has in the column _path3.
Furthermore, I can use a raw query (using connection.cursor()) and I can get the last row. But it's only the raw data, and I need a model object. Oh and using .extra() hasn't worked either.
Why can't I get the last row? (until I reboot the server)
Thanks.
EDIT:
The different "_path*" variables are needed for something else, so an abstract base class will not help in my case, but that's another topic.
As for the db_column='path', I have it that way so that raw queries are more streamlined and I have tried removing that (so that the column is "_path1", "_path2", etc), but the issue still persists. The part that is most confusing is that a raw query works, and restarting the server fixes it (until a new row is inserted, then that last one isn't seen).
EDIT2:
So I discovered what was happening. The important thing I forgot was how each of the tables were tied together.
If I have a base class:
class A
A subclass:
class B (A)
Another subclass:
class C (B)
I have tables linked like so:
A -> B -> C
Lets say I have 2 rows in each table (each one representing a instance of the class):
row 1 A: Name="Gerald" -> B: Age="25" -> C: Gender="Male"
row 2 A: Name="Janet" -> B: Age="24" -> C: Gender="Female"
If row two in table B is deleted, there is a break in the link that points to table C.
So I basically chopped of the torso of the class. 1/3 of the data is missing. And so, django reports it as non-existent.
So, be sure you are careful when deleting entries manually. You shouldn't have this issue with django as it should keep track of all of it for you.
First thing I notice is that you have two models that are inheriting from other classes and adding their own fields, but they're using the same db_column. A cleaner way to achieve this (if you're not directly using main_menu) is with an Abstract Base Class.
Effectively, your language2 model has these fields:
_path1 = models.CharField(db_column='path', max_length=Global.MAX_FILE_PATH_LENGTH, unique=True)
_path2 = models.CharField(db_column='path', max_length=Global.MAX_FILE_PATH_LENGTH, unique=True)
_path3 = models.CharField(db_column='path', max_length=Global.MAX_FILE_PATH_LENGTH, unique=True)
main_menu_blah = models.CharField(max_length=30, default='')
language_blah = models.CharField(max_length=30, default='')
language_blah2 = models.CharField(max_length=30, default='')
Also, Python does not require a semicolon at the end of each statement.
I'm trying to store sections of a document in a Django app. The model looks like:
class Section(models.Model):
project = models.ForeignKey(Project)
parent_section = models.ForeignKey('Section', blank=True, null=True, related_name='child_set')
predecessor_section = models.ForeignKey('Section', blank=True, null=True, related_name='predecessor_set')
name = models.CharField(max_length=100)
text = models.TextField(blank=True, null=True)
I create a whole lot of sections, link them (parent_section, predecessor_section) and store them by calling each of their save methods. However, when I look into the table after saving it, the parent_section_id and the predecessor_section_id are not set, even though I had objects attached to them before saving.
I assume it has to do with the fact that some parent_section instances don't have an id assigned as their instance hasn't been stored yet, but using manual transactions couldn't solve the problem.
Any thoughts on that?
Cheers,
Max
objects do not have an id until you save them in Django ORM.
So I'd say you need to save() the object, then reference it in your parent/child sections (and re-save the sections).
However, another option to storing prec and next as pointers is to store an sequence_index (spaced by 10 to allow further inserts wiothout reordering) and order by this index.
Try doing a save() on all the objects, then update their relations, and then save() all of them again.
When you assign a foreignkey, the related (target) object's id is copied. since at the moment of assigning the relations (parent_section, predecessor_section) the related objects don't have an id yet, you get a funky result:
A = Section(name='A')
B = Section(name='B')
B.parent_section = A
A.save()
B.save()
B.parent_section # this will say A
B.parent_section_id # this will say **None**
But this should work:
A = Section(name='A')
B = Section(name='B')
A.save()
B.save()
B.parent_section = A
B.parent_section # this will say A
B.parent_section_id # this will say A.id
B.save() # don't forget this one :)