class Revision(models.Model):
date_created = models.DateTimeField(
db_index=True,
verbose_name=_("date created"),
help_text="The date and time this revision was created.",
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=True,
null=True,
on_delete=models.SET_NULL,
verbose_name=_("user"),
help_text="The user who created this revision.",
)
comment = models.TextField(
blank=True,
verbose_name=_("comment"),
help_text="A text comment on this revision.",
)
I need to get the latest entry for each user. But I can’t build a normal query. I am using sqlite3 database
You can do something like this:
Revision.objects.values('user').annotate(Max('date_created'))
Related
I need a help, please. So I have 2 classes
class Pokemon(models.Model):
"""Pokemon object"""
pokedex_creature = models.ForeignKey(
PokedexCreature,
on_delete=models.CASCADE,
)
trainer = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
blank=True,
null=True,
)
team = models.ForeignKey(
Team,
on_delete=models.SET_NULL,
blank=True,
null=True,
)
and
class Team(models.Model):
"""Team model"""
name = models.CharField(max_length=100)
trainer = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
blank=True,
null=True,
)
pokemon_1 = models.ForeignKey(
Pokemon,
on_delete=models.SET_NULL,
blank=True,
null=True,
)
pokemon_2 = models.ForeignKey(
Pokemon,
on_delete=models.SET_NULL,
blank=True,
null=True,
)
pokemon_3 = models.ForeignKey(
Pokemon,
on_delete=models.SET_NULL,
blank=True,
null=True,
)
I want to put a ForeingKey of Team to Pokemon model when I add this Pokemon to the team.
I use ForeingKey in Team model to assign a Pokemon to this Team so I would like to make the same this Pokemon instance to see to what Team he is assigned.
What is the best way to do that?
I use Django 3.2.12 and REST Framework 3.13.1
When accessing my ExternalRecord model via the django admin screen, or by querying ExternalRecord.objects.all(), I receive the error: psycopg2.errors.UndefinedColumn: column integrations_externalrecord.oppcontact_id does not exist
I am building an integration functionality, and we have a junction table that houses an external id and the instance in our database that corresponds to this external id, set up like so:
class ExternalRecord(UUIDPrimaryKey, CreatedModifiedMixin, models.Model):
integration = models.ForeignKey(
to=Integration,
related_name='external_records',
on_delete=models.CASCADE
)
emailuser = models.ForeignKey(
"accounts.EmailUser",
related_name='external_records',
null=True,
blank=True,
on_delete=models.CASCADE
)
institution = models.ForeignKey(
"institutions.Institution",
related_name='external_records',
null=True,
blank=True,
on_delete=models.CASCADE
)
oppcontact = models.ForeignKey(
"opp_contacts.OppContact",
related_name='external_records',
null=True,
blank=True,
on_delete=models.CASCADE
)
external_record_id = models.CharField(
max_length=1000
)
and so on...
When I view the OppContact model either by viewing in the django admin screen or with OppContact.objects.all(), I see that the model has a field for "id". When I rollback to the migration before applying the oppcontact field, everything returns to work as normal, meaning I can query/view ExternalRecords without getting an error.
This is my OppContact model:
class OppContact(UUIDPrimaryKey):
company = models.ForeignKey(
"accounts.Company",
on_delete=models.CASCADE,
blank=True,
null=True
)
first_name = models.CharField(
max_length=100
)
last_name = models.CharField(
max_length=100
)...
And this is another model to which my ExternalRecord can be linked, Institution:
class Institution(UUIDPrimaryKey, CreatedModifiedMixin, models.Model):
company = models.ForeignKey(
"accounts.Company",
related_name='institutions',
null=False,
blank=False,
on_delete=models.CASCADE,
)
owner = models.ForeignKey(
"accounts.EmailUser",
related_name='institutions',
null=True,
blank=True,
on_delete=models.CASCADE,
)
name = models.CharField(max_length=100, null=False, blank=False)....
The only difference I see between the models is the OppContact doesn't have the CreatedModifiedMixin or models.Model, but I thought UUIDPrimaryKey extended models.Model, so I didn't think it mattered.
I have been stuck on this for several days, so any pointers in the right direction would be helpful (: Thank you all!
For all those following along at home, the issue was actually with a constraint I added to the ExternalRecord model, which caused the migration to fail, which is why the column wasn't found.
I want to sort Groups with their 'is_favorite' boolean field from model GroupUser. I have two models GroupUser where there is a foreign key to Group model, now when I query Group.objects.filter(is_active=True).order_by('groupuser__group_id__is_favorite')
I get groups multiple times. I tried to user distict() on final queryset still no luck. Pls suggest any other way or possible solution. TIA.
class Group(models.Model):
group_name = models.CharField(
max_length=250)
context_type = models.ForeignKey(
"contenttypes.ContentType",
on_delete=models.DO_NOTHING,
blank=True,
null=True,
related_name="content_type")
context = models.IntegerField(
blank=True,
null=True)
privacy_type = models.ForeignKey(
"commans.PrivacyType",
on_delete=models.DO_NOTHING,
blank=True,
null=True,
related_name="group_privacy_id")
is_active = models.BooleanField(
default=True,
help_text="Is Group Active")
class GroupUser(models.Model):
group = models.ForeignKey(
"Group",
on_delete=models.DO_NOTHING,
blank=True,
null=True,
related_name="groupuser_group_id")
user=models.ForeignKey(
"auth_module.User",
on_delete=models.DO_NOTHING,
blank=True,
null=True)
is_favorite = models.BooleanField(
default=False,
blank=True,
null=True)
```
We can use an annotation to count the number of favourites each Group has. Then we can use this annotation to order by
from django.db.models import Sum
Group.objects.filter(
is_active=True
).annotate(
total_favorites=Sum('groupuser_group_id__is_favorite')
).order_by(
'-total_favorites'
)
I want to make a filter on a nested Model with the Django reverse relation. Below is the sample models I have :
class ProcessVersion(TimeStampedModel):
tag = models.CharField(_('Tag Name'), max_length=48)
status = FSMField(
_('Status'), max_length=12, choices=VERSION_STATUS_CHOICES,
default=VERSION_STATUS_IN_EDITION)
class Step(models.Model):
version = models.ForeignKey(
ProcessVersion, verbose_name=_('Process Version'),
on_delete=models.CASCADE, related_name='steps', blank=True,
null=True)
is_active = models.BooleanField(
_('Is active'), default=False)
title = models.CharField(_('Title'), max_length=32)
class Block(models.Model):
step = models.ForeignKey(
Step, verbose_name=_('Loan Process Step'), on_delete=models.CASCADE,
related_name='blocks', blank=True, null=True)
is_active = models.BooleanField(
_('Is active'), default=False)
title = models.CharField(_('Title'), max_length=128, blank=True)
The first scenario was accessing the Step through it's related name and it worked :
process_version = ProcessVersion.objects.get(id=process_version_id)
steps = process_version.steps.get(id=param_id)
meaning that I passed through ProcessVersion to get the Step.
Now, my question is what if I want to get the Block but passing through ProcessVersion with it's id , how can I query that ?
I have a model called Order with a datetime field called start. I can read and write from/to that field no problem.
However, I just created a ModelForm and specified start as one of the fields=() in Meta and I get:
Unknown field(s) (start) specified for Order
I've made sure it is not a typo by copying and pasting the field name. If I remove that field, it works.
Here is the exact ModelForm
class OrderForm(ModelForm):
class Meta:
model = Order
fields = ('details', 'start', 'quantity', 'total')
EDIT added more details:
I tried using exclude = () to exclude all fields except those I need, and start does not appear in the form even though I don't exclude it.
Here is the model:
class Order(MyModel):
user = models.ForeignKey(User, )
invoice = models.ForeignKey(Invoice, )
unit_price = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True, )
subtotal = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null =True, )
tax = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True, )
misc = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True, )
total = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True, )
start = models.DateTimeField(auto_now_add=True, blank=True, null=True, )
end = models.DateTimeField(editable=True, blank=True, null=True, )
duration = models.PositiveSmallIntegerField(blank=True, null=True, )
quantity = models.PositiveSmallIntegerField(blank=True, null=True, )
notes = models.CharField(max_length=256, blank=True, null=True, )
details = models.CharField(max_length=64, blank=True, null=True, )
configured = models.BooleanField(default=False, )
Remove:
auto_now_add=True
Model field reference | Django documentation | Django :
As currently implemented, setting auto_now or auto_now_add to True
will cause the field to have editable=False and blank=True set.
I removed the auto_now_add=True and the problem is solved.
Thanks for everyone's help.
Maybe you have editable=False defined for the start field?
According to documentation:
If False, the field will not be displayed in the admin or any other ModelForm. Default is True.