here's what I have now:
im = get_object_or_404(Images, uid=uid)
next = get_object_or_404(Images, pk=im.pk+1)
but if I deleted one instance always the next will be 404 because of the pk, so how can I get directly the next?
You can use .get_next_by_FOO
For every DateField and DateTimeField that does not have null=True, the object will have get_next_by_FOO() and get_previous_by_FOO() methods, where FOO is the name of the field. This returns the next and previous object with respect to the date field, raising a DoesNotExist exception when appropriate.
For example, when your Images model has created_at with models.DateTimeField;
class Images(models.Model):
....
created_at = models.DateTimeField(auto_now_add=True)
So, you can use with;
img = get_object_or_404(Images, uid=uid)
next_img = img.get_next_by_created_at()
this is what worked for me:
next = Images.objects.filter(pk__gt=im.pk).order_by('pk').first()
Related
I would like to filter based on #property field to generate a queryset. My model as below.
class PED(models.Manager):
def ped(self):
ped = self.provision_start_date + relativedelta(months = self.po_duration )
return ped
`class PrHW(models.Model):
po_duration = models.IntegerField(null=True)
provision_start_date = models.DateField(null=True, blank=True)
description = models.TextField(blank=True, null=True)
#property
def provision_end_date(self):
provision_end_date = self.provision_start_date + relativedelta(months=self.po_duration)
return provision_end_date`
objects = models.Manager()
ped = PED()
Since "provision_end_date" is a calculated field, it is not part of PrHW.objects.all() and hence I am unable create queryset using it as a filter option (eg, generate list of PrHW objects where provision_end_date is less than today - This generates error that "provision_end_date" is not a valid field; which was expected). I tried creating custom model manager but still I am unable to access either the #property field or other fields such as "provision_start_date" in the custom manager. May be this would be straight forward but even after several searches, unable to get the hang of it. Any help is appreciated.
I have included the models manager code as well where I have tried to move the calculation of provision_end_date functionality. When I run PrHW.ped.ped(), it throws me the error: "AttributeError: 'PED' object has no attribute 'provision_start_date'" where provision_start_date is db field.
The #property decorator allows you to access the model field as if it was a regular property.
This means you can call provision_start_date as if it were a variable:
start_date = prwh.provision_start_date
Also, you can do the checks like this
if prwh.provision_start_date < today:
"return something"
Model:
class List(models.Model):
Lid = models.AutoField(primary_key=True)
Name = models.CharField(max_length=100)
addr1 = models.CharField(max_length=100)
addr2 = models.CharField(max_length=100)
City = models.CharField(max_length=40)
State = models.ForeignKey(State,blank=True, on_delete=models.DO_NOTHING, default=None,to_field="state",db_column="State") #,to_field="state",db_column="State"
Below is the error appears when tried to migrate,
IntegrityError(
django.db.utils.IntegrityError: The row in table 'list' with primary key '1' has an invalid foreign key: list.State contains a value '' that does not have a corresponding value in State.state.
How to fix this issue? I did add those 'blank=True' and on_delete=models.DO_NOTHING after searching for a solution in google, still no luck.
If you want have row from List and 1 row from State.
It can be o2o-key (don't matter which model), or you can use Foreign-key in List.
But: DB-Table State should have in your db_column="State" only unique keys.
If you want to have every row from List and some rows from State.
Foreign key should be in State model, not in List.
After that: On migration you should convert column list.state to value_type like in state.state.
For example you have type(list.state) = string and type(State.state) = integer. It can works without it, i know, but it is better to check it on migration.
if you have in list.state default=None, also you can convert every_list_row.state = '' to every_list_row.state = None, to avoid problem in future, on export etc.
If you receive ForeignObjectException - object not exists on list_row.state:
You can create something like that:
#property
def get_state(self):
return hasattr(list_row, 'state') and list_row.state or ''
and after that: list_row.get_state
I did a database flush to reset my database. I am getting this error when I try to do the following code.
Code that throws error:
try:
print("Attempting to load %s" % store.get('name'))
# THIS NEXT LINE THROWS ERROR
store_obj = Store.objects.get(name=store.get('name'))
except Store.DoesNotExist:
store_obj = Store(name=store.get('name'),
last_updated=last_updated,
address=store.get('address'),
city=store.get('city'),
state=store.get('state'),
zip_code=store.get('zip_code'))
Error:
Exception Type: DataError at /stores/
Exception Value: value too long for type character varying(2)
\d of stores_store
Model in django:
class Store(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
created_at = models.DateTimeField(default=datetime.now, blank=True)
last_updated = models.DateTimeField(default=datetime.now, blank=True)
# Address
address = models.CharField(_("address"), max_length=128)
city = models.CharField(_("city"), max_length=128)
state = USStateField(_("state"))
zip_code = USZipCodeField(_("zip code"), max_length=5)
def __str__(self):
return self.name
As you can see the store name is a VARCHAR of 200, not 2. However, I cannot complete this get operation without getting this error. I tried another flush and makemigrations -> migrate but still have no luck. What else can I try?
Thanks!
the column "state" has USStateField(_("state")) which I assume is varying(2), are you trying to add a tuple which state is bigger than varying(2)?
I can suggest you to change the USStateField(_("state")) to a CharField or to put a max_length.
If that doesn't work you can try to delete the migrations history to make them again. Inside the app folder in migrations delete all the files that look like 0001_initial.py, don't delete the init.py inside the migrations folder, hope it helps :D
Go to your migrations file and track the value stated in the error within those files and increase the value to match it with the one in your models.py file and your database
I have the following 2 models:
class Note(models.Model):
name= models.CharField(max_length=35)
class ActionItem(models.Model):
note = models.models.OneToOneField(Note, on_delete=models.CASCADE)
target = models.CharField(max_length=35)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)
In other models(based on some conditions) I trigger an utility function that create a Note:
def create_note(target=None, action=None):
note = Note(target=target, name=name).save()
transaction.on_commit(
ActionItem(note=note, target=target).save())
I get the following error:
null value in column "note_id" violates not-null constraint
DETAIL: Failing row contains (6, null).
If I use:
So, I presume the error appears because save, doesn't return anything.
I need the Note to pass it as a FK to ActionItem, an be sure it was saved.
The .save() method of a model does not return anything, hence your note variable is None, and as a result the creation of an ActionItem object gets a None for note reference, and thus raises na error.
We can solve it by using Note.objects.create(..) which .saves() and returns the object:
def create_note(target=None, action=None):
note = Note.object.create(target=target, name=name)
transaction.on_commit(lambda: ActionItem.object.create(note=note, target=target))
Alternatively, we can first construct the object, and then .save() it:
def create_note(target=None, action=None):
note = Note(target=target, name=name)
note.save()
transaction.on_commit(lambda: ActionItem.object.create(note=note, target=target))
You can use create function instead of save function
def create_note(target=None, action=None):
note = Note.objects.create(name=name)
actionItem = ActionItem.object.create(note=note, target=target)
How to get only recently added Order?
class Order(models.Model):
STATUSS = (
(u'E', u'Expected'),
(u'S', u'Sent'),
(u'F', u'Finished'),
)
who = models.ForeignKey(User, related_name='Owner')
products = models.TextField()
date = models.DateTimeField(auto_now_add=True)
send = models.ForeignKey(Send)
status = models.CharField(max_length=2, null=True, choices=STATUSS, default='O')
I prefer auto-increment pk, then
Order.objects.latest('pk')
It's simpler, indexed and is ready as long as the default surrogate primary key is used.
If by recently you mean the most recent order regarding the date it was added then you can use:
Order.objects.order_by('-date')[0]
If your definition of "recently" is "the last added", you can use latest()
Order.objects.latest('date')
or just
Order.objects.latest()
if you have
class Meta:
get_latest_by = 'date'
in your model. This is from the django docs, https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.latest
If you want more than one of the most recent, say everything from the last 5 days:
import datetime
Order.objects.filter(date__gte=datetime.date.today() - datetime.timedelta(days=5))
or if you want the last 10 records regardless of how recent, then:
Order.objects.order_by('-date')[10]